简体   繁体   English

Objective-C if语句评估

[英]Objective-C if statement evaluation

I want to check this statement: 我要检查以下语句:

 if([optionsDictionary objectForKey:@"showTimes"] 
     && [[optionsDictionary objectForKey:@"showTimes"]isEqualToString:@"1"])

App crashes. 应用程序崩溃。 The question is - does Objective-C check all conditions? 问题是-Objective-C是否检查所有条件? Because in C# if 1 condition fails then second is not checked at all 因为在C#中,如果1个条件失败,则根本不检查第二个

Use [[optionsDictionary objectForKey:@"showTimes"] boolValue] to determine whether it's 0 or 1. 使用[[optionsDictionary objectForKey:@"showTimes"] boolValue]确定它是0还是1。

Modify your condition as 修改条件为

if([optionsDictionary objectForKey:@"showTimes"] 
 && (1 == [[optionsDictionary objectForKey:@"showTimes"] boolValue]))

(1) If statements and the && and || (1)if语句以及&&和|| operators are evaluated exactly the same in Objective-C as they are evaluated in C, C++ or Java. 在Objective-C中对运算符的评估与在C,C ++或Java中评估的完全相同。

(2) If you send any message to an object that is nil, the result will be 0 / NO / nil. (2)如果将任何消息发送到对象nil,则结果将为0 / NO / nil。 Therefore, the && is pointless. 因此,&&是毫无意义的。 You could have just written 你可能已经写了

if ([[optionsDictionary objectForKey:@"showTimes"]isEqualToString:@"1"])

By the way, it is less confusing to yourself and everyone else to check whether an object is nil by comparing it to nil. 顺便说一下,通过将对象与nil进行比较来检查对象是否为nil,对您自己和其他所有人都不会造成混淆。

(3) Sending a method isEqualToString to an object that is not an NSString will crash. (3)向不是NSString的对象发送isEqualToString方法将崩溃。 The crash will tell you what message you sent to what kind of object. 崩溃将告诉您发送给哪种对象的消息。 NSCFBoolean is an NSNumber with a boolean value, so it crashes. NSCFBoolean是具有布尔值的NSNumber,因此会崩溃。

You need to either know what's in your dictionary, or check it. 您需要知道词典中的内容或进行检查。 If you didn't put the values into the dictionary yourself, you don't know what's in there. 如果您自己没有将值放入字典中,那么您将不知道其中的内容。 For example, if you used a parser to parse a JSON document, your current code will crash again if the JSON document contained a null value. 例如,如果您使用解析器来解析JSON文档,则当JSON文档包含空值时,当前代码将再次崩溃。 Or a dictionary. 或字典。

The best thing to do, because this will happen to you again and again, is to write an NSDictionary category with a method boolValueForKey: which does all the checking for you. 最好的办法是,这会一次又一次地发生在您身上,这是使用方法boolValueForKey:编写一个NSDictionary类别,该方法为您完成所有检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM