Re: returning nil on initialization
Re: returning nil on initialization
- Subject: Re: returning nil on initialization
- From: Bill Cheeseman <email@hidden>
- Date: Thu, 01 Apr 2004 19:45:31 -0500
on 2004-04-01 5:26 PM, Chris Hanson at email@hidden wrote:
>
On Apr 1, 2004, at 2:21 PM, Daniel Waylonis wrote:
>
> I'm under the impression that the result of [super init] and the
>
> variable self will always be the same.
>
>
Not necessarily. [super init] can return a different self,
>
particularly when class clusters are involved. This is why you should
>
never write the following:
>
>
NSString *s = [NSString alloc];
>
[s init];
>
>
The first expression may return one object of one type of internal
>
NSString subclass, while the second expression may return a different
>
object of a different type of internal NSString subclass. If you
>
follow the idioms properly, you won't be bitten by this.
That is exactly how I have always understood it. The documentation tells you
that your subclass's init... methods should be sure to release the allocated
object and return nil in the event that your initialization routines fail.
Presumably, Apple's own built-in Cocoa classes obey this rule.
Thus, when you want to create a new object of class myClass in your code,
you can count on safely doing this:
myClass *myObj = [[myClass alloc] init];
if (myObj) {
// do something here with myObj
[myObj release];
}
If the 'myObj' object is nil because the -init failed and deallocated what
was just allocated with [myClass alloc], you don't need to release the
'myObj' object outside the 'if (myObj)' block because it was already
released in the -init method.
Is this correct?
--
Bill Cheeseman - email@hidden
Quechee Software, Quechee, Vermont, USA
http://www.quecheesoftware.com
The AppleScript Sourcebook -
http://www.AppleScriptSourcebook.com
Vermont Recipes -
http://www.stepwise.com/Articles/VermontRecipes
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.