Why should I call self=[super init]

You mean why

self = [super init];

rather than

[super init];

Two reasons:

  1. in initialisation, failure is indicated by returning nil. You need to know if initialisation of the super object failed.
  2. the super class might choose to replace the self returned by +alloc with a different object. This is rare but happens most frequently with class clusters.

Edited in response to Michael’s comment:

I can understand why I need to save and return [super init]. But is it just convention and good looking makes us use self as a temporary variable to pass result along?

No. Instance variables are accessed relative to the self pointer, so in the following:

-(id) init
{
    self = [super init];
    if (self != nil)
    {
        myBoolIvar = YES; 
       // The above is an implicit version of self->myBoolIvar = YES;
    }
    return self;
}

self has clearly got to point to the right block of memory i.e. the one you are going to return.

The other point is that if super init returns different class instance then the rest of the code after that line may not even make sense, lead to memory leaks and crashes, not even talking about the object instantiated from that class.

That could be a problem. If I subclassed NSNumber and [super init] decided to return an NSString (which it could – there’s nothing to stop it) that would clearly be a disaster. Whatever super returns from -init must be “compatible” with the subclass in the sense of providing space for ivars and being further subclassible or it’s a horrendous bug (unless, of course, the problem is documented). So, in general, you don’t need to worry about checking the class. However, do read the documentation. See for instance the section on subclassing NSString in NSString’s docs.

Leave a Comment