在子类中覆盖init

在Objective-C中,是否有必要重写一个子类的所有inheritance构造函数来添加自定义的初始化逻辑?

例如,对于具有自定义初始化逻辑的UIView子类,以下是否正确?

 @implementation CustomUIView - (id)init { self = [super init]; if (self) { [self initHelper]; } return self; } - (id)initWithFrame:(CGRect)theFrame { self = [super initWithFrame:theFrame]; if (self) { [self initHelper]; } return self; } - (id)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (self) { [self initHelper]; } return self; } - (void) initHelper { // Custom initialization } @end 

每个Cocoa Touch(和Cocoa)类都有一个指定的初始化器; 对于UIView ,如本文档中所述 ,该方法是initWithFrame: 在这种情况下,你只需要重写initWithFrame ; 所有其他的电话将逐渐下降,并最终打这个方法。

这超出了问题的范围,但是如果你最终创build了一个具有额外参数的自定义初始值设定项,那么在分配self ,应该确保为超类指定了初始值设定项,如下所示:

 - (id)initWithFrame:(CGRect)theFrame puzzle:(Puzzle *)thePuzzle title:(NSString *)theTitle { self = [super initWithFrame:theFrame]; if (self) { [self setPuzzle:thePuzzle]; [self setTitle:theTitle]; [self initHelper]; } return self; } 

一般来说,你应该遵循指定的初始值规则。 指定的初始化程序是init,它涵盖了所有实例variables的初始化。 指定的初始化程序也是一个类的其他init方法调用的方法。

苹果有关指定初始化程序的文档 。

initWithFrame:是NSView类的指定初始值设定项。 苹果的Cocoa文档总是明确提到了一个类的指定初始化器。

initWithCoder:在这里讨论SO 。

在使用Interface Builder的情况下,被调用的是:

 - (id)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; if (self) { //do sth } return self; }