检查零值是否正确?

时间:2011-02-07 04:28:31

标签: iphone null

嗨我只是想知道这是否正确,我们可以通过这种方式检查nil吗?if(self.spinner==nil)

感谢

if (self.spinner == nil) {
    self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    //.............needs work.............  
    CGRect center = [self.view bounds];
    CGSize winCenter = center.size;
    CGPoint pont = CGPointMake(winCenter.width/2,winCenter.height/2);
    //CGPoint pont = CGPointMake(10,40);
    [spinner setCenter:pont];
    [self.view addSubview:spinner];
    [self.spinner startAnimating];
} else {
    [self.spinner startAnimating];
}

3 个答案:

答案 0 :(得分:2)

是的,这是对的。你甚至可以写得更短:

if ( !self.spinner ) {
...
}

答案 1 :(得分:2)

是的,但我稍微改了一下:

if (!self.spinner) {
    self.spinner = [[UIActivityIndicatorView alloc] ...
    ...
}
// Do this outside the test, thus avoiding the else.
[self.spinner startAnimating];

答案 2 :(得分:0)

是的,检查nil绝对有效。在标题深处的某处,nil被定义为(id)0,这意味着您可以使用指针相等性将其与任何Objective-C对象进行比较。

精明的观察者会意识到,因为nil为零,而Objective-C条件控制结构(ifwhile等)接受任何int - 就像数据类型,使用对象指针作为条件本身将在对象为非nil时传递,如果对象为nil则失败:

if (self.spinner) // implicitly checks that self.spinner is non-nil
if (!self.spinner) // implicitly checks that self.spinner is nil

根据您作为程序员的背景,您可能喜欢或不喜欢此功能。但它的工作方式与nil的效果相同。

相关问题