Re: Memory Allocation
Re: Memory Allocation
- Subject: Re: Memory Allocation
- From: "Shawn Erickson" <email@hidden>
- Date: Wed, 16 Jul 2008 15:21:08 -0700
On Wed, Jul 16, 2008 at 2:19 PM, Michael Ash <email@hidden> wrote:
> On Wed, Jul 16, 2008 at 2:38 PM, Kyle Sluder
> <email@hidden> wrote:
>> On Wed, Jul 16, 2008 at 2:02 PM, Alexandre Badez
>> <email@hidden> wrote:
>>> -(id)init
>>> {
>>> if (![super init])
>>> return nil;
>>
>> You must always assign self to the result of [super init]. If anyone
>> (*cough* Wil Shipley *cough*) tells you otherwise, they may
>> inadvertently set you up for some seriously subtle errors.
>
> Can you explain this, in particular how the "standard" initializer
> sets you up for fewer seriously subtle errors than this one?
>
> It seems to me that the possible return values from the [super init]
> call can be broken into three categories:
>
> A) self
> B) nil
> C) Something Else
>
> A is obviously the common case, and B is the standard way to signal a
> failure. Both the standard initializer and this one handle A and B
> just fine, so they aren't all that interesting. That leaves us with C.
>
> In the case of C, this initializer crashes and burns. If [super init]
> returns another object, then it will free self, and then you'll be
> accessing self after it's freed. Obviously this is bad.
That is why you set self to the return value of [super initXxx] and
check to ensure it isn't nil. Remember that "self" is a local var
that, while passed to the method via a hidden parameter, can still be
modified as needed while in the scope of the method.
> However, the standard initializer *also* crashes and burns in the case
> of C. The Something Else could be anything. It may not even be an
> instance of your class, in which case you're accessing ivars that
> aren't there, and you'll fail horribly.
It could be a dynamically generated subclass of your class that has
the ivars you expect.
-Shawn
_______________________________________________
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