简体   繁体   中英

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;
}

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.

-(id)initWithSomething:(Something *)somet {
    if ((self = [super initWithSomething:somet])) {
      // ...
    }    
    return self;
}

One-and-only-one method should be your "designated initializer" for a class. All other initializers should call that one, and the designated initializer should call super 's designated initializer. (This is a general rule; there are a few exceptions such as in initWithCoder: , but it is the normal approach.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM