On May 19, 2009, at 9:37 AM, Jean-Daniel Dupas wrote:

Le 19 mai 09 à 18:24, Reza Farhad a écrit :
Hi all

we have an object that gets initialized like most other objects

-(id)init
{
        self = [ super init ];
        if ( self ){
                ...do something;
        }
        return self;
}

if [ super init ] returns nil does this cause a leak, as the memory has already been created by calling alloc when trying to create the object

AnObject        *object = [[ AnObject alloc ] init ];

I am sure the answer is simple but this suddenly stumbled me.

Thanks

The answer is in the Cocoa Fundamentals Guide > Cocoa Objects > Object Creation > Implementing Initializer

with a lots of other useful info.

http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html


There was a thread in ObjC-language about this a while back:
http://lists.apple.com/archives/ObjC-Language/2008/Sep/msg00132.html

In the followup, an Apple runtime engineer recommends calling [super dealloc] before returning nil, saying "[self dealloc] or [self release] are bad because they might call some subclass's -dealloc method even though the subclass's -init hasn't done anything yet."

Of course, in practice [self release] should usually work just fine as well, and avoids breaking the "never call dealloc except in -dealloc" taboo. And indeed, this is what the documentation and sample code do as well. I think you would be reasonably justified to do either. I'm still debating this myself for our company's code, but the fact is that they both work in most situations.

hope this helps,
-natevw

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to