Re: self = [super init] debate.
Re: self = [super init] debate.
- Subject: Re: self = [super init] debate.
- From: Quincey Morris <email@hidden>
- Date: Sun, 10 Feb 2008 17:32:30 -0800
On Feb 10, 2008, at 13:44, Jens Alfke wrote:
The real killer argument for reassigning 'self' is that the call to
[super init] might fail, returning nil. If this happens, the
superclass init method has released/dealloced the object (to avoid a
leak) so your 'self' is now a dangling pointer to freed memory. In
this case you must immediately return nil instead of doing any more
setup.
And -init methods do return nil for reasons other than out-of-
memory. For example, -[NSString initWithUTF8String:] returns NIL if
the parameter isn't valid UTF-8, and -[NSDictionary
initWithContentsOfFile:] returns nil if the file isn't found or
isn't a plist.
Just to follow up on a couple of minor points ...
-- IIRC, in the discussion on Shipley's blog, his preferred coding
pattern was:
if (![super init])
return nil;
which does at least handle the nil-return case correctly. It
mishandles the returns-a-different-instance case, as you noted before.
-- Someone did an automated check of every Cocoa class in Tiger (maybe
it was every subclass of NSObject, I don't remember exactly now) and
counted the number of classes for which the receiver of [super init]
was different from the returned value. The answer was 0.
That may comfort anyone who wants to leave out the 'self =', but it's
hardly a reliable argument. The number of dead people reading this
discussion is also 0 (afaik), but I wouldn't take that as proof of
immortality.
-- Some classes cannot be subclassed -- cluster classes like NSArray,
for example. These classes prove nothing one way or another about
writing subclass initializers.
Classes that return a singleton -- such as NSNull -- can't be
subclassed either, so they're also ineffective examples.
_______________________________________________
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