• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: -(id)init methods, NSExceptions, and returning nil
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: -(id)init methods, NSExceptions, and returning nil


  • Subject: Re: -(id)init methods, NSExceptions, and returning nil
  • From: Jens Alfke <email@hidden>
  • Date: Mon, 27 Jun 2011 12:20:27 -0700

On Jun 27, 2011, at 6:22 AM, William Squires wrote:

> What if I have an init method, and - in the above '// Do something here' section - my initializations fail (maybe a resource can't be located/loaded) - should I raise an NSException, or set self=nil so that any subclasses will get a nil when they call my class' init through the [super init] part?

If your initializer fails, it should call [self release], so self doesn’t get leaked, and return nil. It shouldn’t raise an exception except for some kind of assertion failure like an invalid parameter.

(If you do this, your -dealloc method must be prepared to handle a receiver that’s been only partially initialized. Usually that’s not an issue since instance variables are pre-initialized to nil.)


Kyle Sluder wrote:
> These are equivalent. All you did was move the self assignment out of
> the if statement.
>
> I actually prefer to use `if (!(self = [super init])) return nil;`.
> Again, it is equivalent.

The original form listed, with the assignment in the ‘if’, will generate a compiler warning* suggesting that you might have typed ‘=‘ instead of ‘==‘. It’s good practice not to put assignments into conditional/loop expressions, because that == vs. = mistake is so easy to make.

—Jens

* At least it will if you have most compiler warnings enabled (e.g. -Wall), which IMHO you should.

Attachment: smime.p7s
Description: S/MIME cryptographic signature

_______________________________________________

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

References: 
 >-(id)init methods, NSExceptions, and returning nil (From: William Squires <email@hidden>)

  • Prev by Date: Re: Event Objects Return 1-Based Y Coordinate Values
  • Next by Date: Re: Event Objects Return 1-Based Y Coordinate Values
  • Previous by thread: Re: -(id)init methods, NSExceptions, and returning nil
  • Next by thread: App Delegate method not being called
  • Index(es):
    • Date
    • Thread