Search code examples
iphoneobjective-coverridingsuperclassmacos

Overriding the init method in a subclass and calling [super initWith:bla], correct way?


I'm subclassing a class. I'm overriding a init method. This one: -(id)initWithSomething:(Something*)somet;

this would look like this (in the subclass)

-(id)initWithSomething:(Something *)somet with:(int)i{

    if (self = [super init]) {
     //do something   
    }

    return self;
}

But now I want to call the init in the superclass too.

How would I now do this? Mayby this way?

-(id)initWithSomething:(Something *)somet with:(int)i{

    if (self = [super init]) {

    }

    [super initWithSomething:somet];

    return self;
}

Solution

  • Typically like this:

    -(id)initWithTarget:(CCNode *)someTarget
    {
        self = [super initWithTarget:someTarget];
        if (self)
        {
    
        }
        return self;
    }
    

    It's the responsibility of super to call the vanilla init selector if it needs to.