Re: Handling [super init] returning nil
Re: Handling [super init] returning nil
- Subject: Re: Handling [super init] returning nil
- From: David Duncan <email@hidden>
- Date: Wed, 29 May 2013 09:58:36 -0700
On May 29, 2013, at 9:36 AM, Peter Teeson <email@hidden> 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
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden