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
.
精彩评论