2

Possible Duplicate:
In Objective-C why should I check if self = [super init] is not nil?

I often see this "if (self = [super init])" construct and I wonder why it's done.

- (id) init {

  if (self = [super init]) {

    // how could self = [super init]; ever fail?

  }

  return self;

}
Community
  • 1
  • 1
Andrew Johnson
  • 13,108
  • 13
  • 75
  • 116
  • Thanks for the comment, this is a dupe. I voted to close rather than delete... I'm not sure what the right way is. – Andrew Johnson Sep 09 '11 at 23:07
  • Same difference. When you vote to close, select "exact duplicate" and you'll be able to specify the message that is a duplicate. The comment is automatic as far as I know. – Jonathan Grynspan Sep 09 '11 at 23:17

3 Answers3

5

Imagine your superclass does this:

- (id)init {
    self = [super init];

    if (self) {
        self->foo = CreateExpensiveWidgetOverTheInternetByTrain();
        if (!self->foo) {
            // widget creation failed, bail out
            [self release];
            self = nil;
        }
    }

    return self;
}

That's how. ;)

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
1

There are a number of ways [super init] could fail:

  1. You are attempting to subclass a "final" class, i.e. one that has been specifically designed not to allow subclassing.

  2. You are out of memory, and out of luck.

  3. In the case of initWithArgument:parameter:; you have supplied invalid arguments or parameters.

Also, other less obvious ways; which are usually the most dangerous ones.

Williham Totland
  • 28,471
  • 6
  • 52
  • 68
0

From the documentation:

In general, if there is a problem during an initialization method, you should call the release method on self and return nil.

There are two main consequences of this policy:

  • Any object (whether your own class, a subclass, or an external caller) that receives nil from an initializer method should be able to deal with it. In the unlikely case that the caller has established any external references to the object before the call, you must undo any connections.
  • You must make sure that dealloc methods are safe in the presence of partially initialized objects.
Community
  • 1
  • 1
James Sumners
  • 14,485
  • 10
  • 59
  • 77