When writing an app, you always have to write alloc/inits, get autoreleased datas returned by the framework classes, ...
This may be 70% of the code, almost each single line of what you write...
So... How do those returned object must be tested, to know if each of these calls have returned a correct object ?
Testing the returned value each time, for each call, and treating the exception if you get nil where you expected an allocated object ? Letting the app crash ?
How this must be done ?
If it's fatal, just abort -- Consider a custom error handler for this case so the info can help you diagnose the issue.
ReplyDeleteIf it's not fatal and you can continue, do so. "Oops, that string could not be converted to some encoding, but that's not a show stopper".
If you can and should present a message instead, do so. Restart may be a safer time to present a message in some cases.
Exceptions in Cocoa -- catch and handle what you must, but Cocoa exceptions are generally "non-recoverable". C++ exceptions are fine, but you may not get too far using them if you are working with ObjC and C++. The problem in its simplest form is that exceptions are not guaranteed to safely cross image boundaries -- ObjC exceptions are C++ exceptions (in OS X 64 bit and iOS).
Error parameters are another way to go. I'm sure you have seen: :(NSError**)outError
The important thing is that you understand the consequences of each approach and write appropriately.
It isn't necessary to check for a nil return value every time you call a function that returns an object. The important thing is to have some sense of when a function is more likely to return a nil object and what the consequences might be for your app.
ReplyDeleteFunctions related to the file system or network are two of the most common types that you will often need to check for nil return values, because the state of those two systems is generally beyond your control, so the resources you are trying to access may be unavailable. A good indication that you should be checking for a nil return value is if the function also takes an NSError ** as an argument.
On the other hand, checking for nil every time you create an NSString or NSArray, for example, is unnecessary because the only reason it would ever return nil is if there has been some kind of programmer error that you should catch during testing anyway.
So I guess my very general advice is not to check for nil when the only practical way it could be nil is if there was a programmer error, but do check for nil when the return object is something that could be nil as a result of some resource not being available (and out of your control).
Also keep in mind that messages to nil are OK in Objective-C, which also eliminates the need for a lot of nil testing in certain cases.