In Objective-C why should I check if self = [super init] is not nil?

For example:

[[NSData alloc] initWithContentsOfFile:@"this/path/doesn't/exist/"];
[[NSImage alloc] initWithContentsOfFile:@"unsupportedFormat.sjt"];
[NSImage imageNamed:@"AnImageThatIsntInTheImageCache"];

… and so on. (Note: NSData might throw an exception if the file doesn’t exist). There are quite a few areas where returning nil is the expected behaviour when a problem occurs, and because of this it’s standard practice to check for nil pretty much all the time, for consistency’s sake.

Leave a Comment