On Jan 29, 2013, at 00:51 , Bob Cromwell <[email protected]> wrote:

> if below code valid ?   All sample codes I could find invoke "self = [super 
> init]" first and then check the input parameter inside "if (self)" block.  
> 
> @implementaion Bla
> 
> - (id)initWithFoo:(NSString *)foo
> {
>    if (foo == nil) {
>        return nil;
>    }
>    self = [super init];
>    if (self) {
>        _foo = foo;
>        .....
>    }
>    return self;
> }
> 
> I had thought there would be memory leak.   "Bla * b =  [Bla alloc ] 
> initWithFoo:nil];" .  However under ARC using Instruments Leaks, there are no 
> leak found. 

No, it's not valid. You can see why if you rewrite this using manual 
retain/release conventions:

   if (foo == nil) {
       [self release];
       return nil;
   }
   self = [super init];

You must (and ARC does) release 'self' before returning nil, to avoid a memory 
leak. The problem is that releasing 'self' will invoke 'dealloc', and you have 
no idea whether it's safe to invoke 'dealloc' if you haven't invoked done 
'[super init]' yet.

Even if your class doesn't have a 'dealloc', you don't know whether a 
superclass or a subclass might have one, now or in the future.

In practice, you *may* get away with doing this, but it's a dangerous idiom to 
use. Much better to check the parameter a bit later:

   if (self) {
       if (foo == nil)
           return nil;
       _foo = foo;
       .....
   }

Note that this isn't guaranteed safe either. The class, or a subclass, may have 
a dealloc that isn't safe if the initialization wasn't completed**. However, 
most dealloc's are written to avoid such problems.


** Here's an example that will crash with an early return:

   if (self) {
       if (foo == nil)
           return nil;
       _foo = foo;
       _bar = malloc (100);
       .....
   }
…..
- (void) dealloc {
    free (_bar);
}


_______________________________________________

Cocoa-dev mailing list ([email protected])

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

This email sent to [email protected]

Reply via email to