开发者

is check nil value this way correct?

hi i just want to know if this is correct, can we check for nil this way-if(self.spinner==nil)?

thanks

if (self.spinner == nil) {
    self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    //.............needs work.............  
    CGRect center = [self.view bounds];
    CGSize winCenter = center.size;
    CGPoint pont = CGPointMake(winCen开发者_如何学编程ter.width/2,winCenter.height/2);
    //CGPoint pont = CGPointMake(10,40);
    [spinner setCenter:pont];
    [self.view addSubview:spinner];
    [self.spinner startAnimating];
} else {
    [self.spinner startAnimating];
}


Yes it's correct. And you can even write shorter:

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


Yes, but I'd change it slightly:

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


Yes, checking against nil is absolutely valid. Somewhere deep within headers, nil is defined as (id)0, which means you can use pointer equality to compare it to any Objective-C object.

An astute observer will realize that since nil is zero and that Objective-C conditional control structures (if, while and the like) accept any int-like data type, using an object pointer as the condition itself will pass if the object is non-nil and fail if the object is nil:

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

Depending on your background as a programmer, you may or may not like this feature. But it works just as much as comparing to nil.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜