Question

This is a general question about handling possible errors where NSError is not being used.

Let's say we have some typical iOS/Cocoa code like this:

NSXMLParser *parser = [[NSXMLParser alloc] initWithData: myData];

The documentation states that an NSXMLParser object will be returned, or "nil if an error occurs".

(For the record, this particular method will happily take nil for the 'data' argument, returning a valid NSXMLParser instance.)

I have noticed that very many iOS developers never check these types of return values. They assume that the class init has always worked. That strikes me as risky, but I'd like to hear the views of seasoned/bitten Cocoa developers.

If I use NSAssert on the return value, that protects me during development, but does little for me when my app is out in the wild.

Should I check for the nil return value, and construct an NSError of my own? Or do something else?

Was it helpful?

Solution

The somewhat unwritten rule is that if an Apple init method can fail in a recoverable manner it will have an NSError parameter. If a method such as NSString fails init things are so bad that recovery really is not possible. Probably so bad that allocation an NSError is not possible much less an NSLog message. The app is probably going to crash soon no matter what you do.

Unfortunately 3rd party classes rarely follow this rule--but you should.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top