Handling [super init] returning nil

  • In Apple's Concepts in Objective-C Programming discussing Issues with Initializers there is this code snippet

    id anObject = [[MyClass alloc] init];
    if (anObject) {
      [anObject doSOmething];
      // more messages…
    } else {
      // handle error
    }

    All the code I Googled does not address the nil case in an error handling way. What one sees is mostly just returning nil.

    In the interest of writing correct code I am curious to know the norm for handling such an error?

    Use NSAssert and/or assert and friends?
    Just log it?
    Put up a Dialog ?

    TIA for your thoughts.

    Peter
  • On May 29, 2013, at 9:36 AM, Peter Teeson <pteeson...> wrote:

    > In Apple's Concepts in Objective-C Programming discussing Issues with Initializers there is this code snippet
    >
    > id anObject = [[MyClass alloc] init];
    > if (anObject) {
    > [anObject doSOmething];
    > // more messages…
    > } else {
    > // handle error
    > }
    >
    > All the code I Googled does not address the nil case in an error handling way. What one sees is mostly just returning nil.
    >
    > In the interest of writing correct code I am curious to know the norm for handling such an error?

    Generally the reason why you see so little handling of this error is that both its handling is context dependent, and that handling it may be in fact impossible.

    Assuming the best case, an -init method returns nil because there is some error that prevents the object from being initialized, the proper course of handling it is going to be entirely application dependent. If that object represents a download you might alert the user that the download is impossible. If it represented a file on disk, you might just create the file and continue on instead. And so on. Hence why it is hard to tell you what to do with the error.

    On the other hand, the worst case is that +alloc returned nil because there is no memory left in your address space. More than likely your application will crash soon trying to do just about anything.

    Typically in cases where there is a possibility for failure that can be recovered from, an NSError object is returned (typically as an additional parameter). If you search for methods that use NSError you'll find copious examples of this. But again how you actually handle the error is entirely context dependent.
    --
    David Duncan
previous month may 2013 next month
MTWTFSS
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    
Go to today