Re: Cleanup inside a failed init method
Re: Cleanup inside a failed init method
- Subject: Re: Cleanup inside a failed init method
- From: Jens Bauer <email@hidden>
- Date: Sun, 7 Dec 2008 00:34:09 +0100
Hi Chuck,
On Dec 6, 2008, at 22:36, Charles Steinman wrote:
The system will only call dealloc if the object is released.
Happily, the object should be released anyway if you plan to return
nil since otherwise you'll leak a half-initialized object every time
the method fails. So you should release self and return nil.
I'm not sure about that. Take a look at this example:
// init only modifies an already allocated buffer.
// ObjC and the O/S does not know what you are going to name your
'init' method:
- (id)initIthMyParameters:(int)aParameter
{
self = [super init];
if(self) // only if super returns a valid buffer
{
parameter = aParameter;
}
return(self);
}
ob = [[MyObject alloc] initWithMyParameters:3];
The result of [MyObject alloc] is passed directly to
initWithMyParameters:.
If alloc fails, it sends NULL as object to init. [NULL init] returns
NULL, no matter which object it is, so does [NULL sniff_sniff].
-However, if +alloc succeeds, you have a buffer, it's passed directly
to initWithMyParameters:.
You're not guaranteed that you will get the same buffer that [MyObject
alloc] returns, because -init* will be able to deallocate it and
return a different (maybe even larger) buffer instead, and perhaps in
a different memory zone.
Who/what is supposed to deallocate the allocated buffer between the
[MyObject alloc] and [myObject init] ?
(How would the 'system' know that the object is to be deallocated?)
The only reason would be that the line...
self=NULL;
...should automatically deallocate the object, and I've never heard
that it did.
The general rule is: Whatever mess you create (inside your method),
you have to cleanup yourself, noone else is doing it for you.
-But if you return NULL from -init, you *must* deallocate self first,
or you will leak memory.
Love,
Jens
_______________________________________________
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