2010-12-05 81 views
36

在Objective-C中,是否有必要覆盖子类的所有继承构造函数以添加自定义初始化逻辑?覆盖子类中的init

例如,将下面是一个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 

回答

38

每个可可触摸(和可可)类具有指定初始化;对于UIView,如in this documentation所述,该方法是initWithFrame:。在这种情况下,您只需要覆盖initWithFrame;最终,所有其他呼叫都会级联并触发此方法。

这超越了问题的范围,但如果你最终创造额外的参数自定义初始化,您应该分配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; 
} 
+1

所以,即使我实例CustomUIView用普通的init,它会调用initWithFrame? – hpique 2010-12-05 16:39:54

4

一般而言,您应该遵循指定的初始化程序约定。指定的初始化程序是init,它涵盖了所有实例变量的初始化。指定的初始化程序也是由类的其他init方法调用的方法。

Apple的documentation关于指定的初始值设定项。

initWithFrame:是一个NSView类的指定初始化。 Apple的Cocoa文档总是明确提到一个类的指定初始化器。

initWithCoder:讨论here on SO

2

在使用界面生成器的情况下,一个被称为是:

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