简体   繁体   English

是(变量)与Objective-C中的if(变量!= nil)相同

[英]Is if (variable) the same as if (variable != nil) in Objective-C

I am getting a EXC_BAD_ACCESS (SIGBUS) on this line in my iPhone project: 我在我的iPhone项目中获得了一行EXC_BAD_ACCESS(SIGBUS):

if (timeoutTimer) [timeoutTimer invalidate];

The thing that has me stumped is that I don't understand how that line could crash, since the if statement is meant to be checking for nil. 令我难过的是我不明白该行怎么会崩溃,因为if语句意味着要检查nil。 Am I misunderstanding the way Objective-C works, or do line numbers in crash statements sometime have the wrong line in them? 我是否误解了Objective-C的工作方式,或者在崩溃语句中的行号有时会出现错误的行?

Just because a variable is set to a value other than nil doesn't mean it's pointing to a valid object. 仅仅因为变量设置为nil以外的值并不意味着它指向有效对象。 For example: 例如:

id object = [[NSObject alloc] init];
[object release];
NSLog(@"%@", object); // Not nil, but a deallocated object,
                      // meaning a likely crash

Your timer has probably already been gotten rid of (or possibly hasn't been created at all?) but the variable wasn't set to nil. 您的计时器可能已经被删除(或者可能根本没有创建?)但是变量未设置为nil。

I just ran into a similar issue, so here's another example of what might cause a check such as yours to fail. 我刚刚遇到了类似的问题,所以这是另一个可能导致检查的例子,例如你的失败。

In my case, I was getting the value from a dictionary like this: 就我而言,我从这样的字典中获取值:

NSString *text = [dict objectForKey:@"text"];

Later on, I was using the variable like this: 后来,我正在使用这样的变量:

if (text) {
    // do something with "text"
}

This resulted in a EXC_BAD_ACCESS error and program crash. 这导致EXC_BAD_ACCESS错误并导致程序崩溃。

The problem was that my dictionary used NSNull values in cases where an object had an empty value (it had been deserialized from JSON), since NSDictionary cannot hold nil values. 问题是我的字典在对象具有空值(它已经从JSON反序列化)的情况下使用NSNull值,因为NSDictionary不能保存nil值。 I ended up working around it like this: 我最终解决了这个问题:

NSString *text = [dict objectForKey:@"text"];
if ([[NSNull null] isEqual:text]) {
    text = nil;
}

They should be the same. 它们应该是一样的。 Perhaps the line number is in fact incorrect. 也许行号实际上是不正确的。

Look for other possible errors near that in your code and see if you find anything. 在代码中查找其他可能的错误,看看是否找到了任何内容。

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

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