简体   繁体   中英

Link superclass init method to designated initializer

Since every class inherits the initializer from the superclass this is how I have linked the default implementation of init to its designated initializer. (It's working.)

Link:

-(id)init {
    return [self initWithItemName:@"Default Value" 
                    valueInDollar:0 
                     serialNumber:@""];
}

Initializer:

-(id)initWithItemName:(NSString *)myItemName
        valueInDollar:(int)myValueInDollar
         serialNumber:(NSString *)mySerialNumber;

My question is, do I ALWAYS have to link my own initializer the way I did it (Link)? So WITHOUT the code below own initializers would never be called? Am I right?

-(id)init {
    return [self myInitMethod......"];
}

If you only initialize your object with initWithItemName , then you don't have to define the init method at all. The initializers are just ordinary methods (no magic involved), so what you call is what will be invoked. But it is good practice to implement the init method so it can be called and the object will be in a consistent state.

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