是(变量)与Objective-C中的if(变量!= nil)相同 [英] Is if (variable) the same as if (variable != nil) in Objective-C

查看:133
本文介绍了是(变量)与Objective-C中的if(变量!= nil)相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在iPhone项目的这一行上获得了一个EXC_BAD_ACCESS(SIGBUS):

I am getting a EXC_BAD_ACCESS (SIGBUS) on this line in my iPhone project:

if (timeoutTimer) [timeoutTimer invalidate];

令我难过的是,我不明白这条线会如何崩溃,因为if语句是为了检查nil。我是否误解了Objective-C的工作方式,或者在崩溃语句中的行号有时会出现错误的行?

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. Am I misunderstanding the way Objective-C works, or do line numbers in crash statements sometime have the wrong line in them?

推荐答案

仅仅因为变量设置为 nil 以外的值并不意味着它指向一个有效的对象。例如:

Just because a variable is set to a value other than nil doesn't mean it's pointing to a valid object. For example:

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

你的计时器可能已经被删除(或者可能根本没有创建?)但是变量没有设置为nil。

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.

这篇关于是(变量)与Objective-C中的if(变量!= nil)相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆