Re: Memory Allocation
Re: Memory Allocation
- Subject: Re: Memory Allocation
- From: "Michael Ash" <email@hidden>
- Date: Wed, 16 Jul 2008 18:38:26 -0400
On Wed, Jul 16, 2008 at 6:21 PM, Shawn Erickson <email@hidden> wrote:
> 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.
I understand that, I was comparing the two cases.
>> 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.
This is indeed the key that I had overlooked.
A colleague pointed out this older post which describes it in more detail:
http://www.cocoabuilder.com/archive/message/cocoa/2008/2/11/198591
In short, [super init] can return an object which can be properly
initialized by your code but which contains more stuff than would be
possible by sticking with the original instance.
Thanks for pointing this out!
Mike
_______________________________________________
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