2010-12-05 79 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; 
}