简体   繁体   中英

Why override the designated initializer of super class?

I was reading the book " Cocoa Design Pattern " and 2 of its point, in chapter 3 (Two-Stage Creation) are making me confused.

  1. Make sure that the superclass' Designated Initializer is overridden to call the new Designated Initializer.

  2. When subclassing, make sure every new initializer that isn't the Designated Initializer calls the Designated Initializer.

My question is how we can call the method for which we don't have the parameters to pass? The book example is being posted below. In this method writer has passed some "static" values, but are we supposed to do this? Or is this always desirable?

My second question is, why I have to override the designated method of super class when I will never call it when I will be initializing my object, other than in my own designated initializer, where I will not be passing any parameters (eg; in case of NSObject)

@interface MYCircle : NSObject {

NSPoint center;

float   radius; 

}

// Designated Initializer 

- (id)initWithCenter:(NSPoint)aPoint radius:(float)aRadius;

@end 

@implementation MYCircle

// Designated Initializer 

- (id)initWithCenter:(NSPoint)aPoint radius:(float)aRadius {

self = [super init];

if(nil != self) {

center = aPoint;

radius = aRadius; 

}

return self; 

}

@end



// Overriden inherited Designated Initializer 
- (id)init {

static const float MYDefaultRadius = 1.0f;

// call Designated Initializer with default arguments

return [self initWithCenter:NSZeroPoint radius:MYDefaultRadius]; 

}

Please also help me to correct my question because I am not sure what I am really asking is a correct question.

Thanks.

The designated initializer is the one that properly configures the object. If you don't choose one init... method as the designated initializer, then you have to make sure that every init... method does the right thing. That generally means that they all have to have the same code, or they all have to call a common setup method. It also means that anyone subclassing your class has to override all the init... methods instead of just one.

By picking (ie "designating") one init... method as the common method that all the others call, you give subclasses a single override point and a single method that their own init... methods can call to ensure that the superclass is properly configured.

If you don't have the data necessary to call the designated initializer, then you don't have the data required to set up the superclass. Somestimes you can choose reasonable default values, as above, but if not then it doesn't make any sense to create the object at hand.

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