开发者

Need an iPhone Programmer judge every step and every pointer == nil?

开发者 https://www.devze.com 2023-03-17 11:51 出处:网络
for example:开发者_开发百科 NSString *myString = [[NSString alloc] init]; if (nil == myString) {

for example:开发者_开发百科

NSString *myString = [[NSString alloc] init];
if (nil == myString) {
    return;
}

Need I do this??Thank you!


No, you don't need to do that, and I can't say I've ever seen code that made pervasive use of that pattern.

Also, the if statement can be shortened to:

if (! myString) {
    return;
}

...which is equivalent though no less superfluous. Checking for nil can be useful, but is typically not done immediately after object instantiation. Instead the typical case is to do it to ensure that an object is not over-released, for instance using a pattern like:

if (myObj) {
    [myObj release];
    myObj = nil;
}

Note that calling any method on nil is allowed in Objective-C, so less harm is caused by an unexpected nil value floating around than in languages like Java where attempting to do anything with a null reference throws an exception.


Objective-C allows to call on nil pointers, that differs the language from many others and allows to skip some checks. Of course, it's still wise to check for == nil in some particular cases, however, you don't have to check every step in the code. Take a look at Apple's documentation and samples and try to follow their style.


Frankly, most iPhone app code produced these days assumes that an out-of-heap condition (the only logical reason for such a simple instantiation operation to fail) never occurs in normal operation. Only when creating large (eg, image) objects might one check for allocation failure.

Of course, init routines can fail for a host of reasons, so checking for nil following a complex instantiation operation may be warranted (depending on the object type). (And remember that many other methods of some objects can return nil under some circumstances as well, so you need to read the specs and code accordingly.)

0

精彩评论

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

关注公众号