2012-05-08 41 views
1

我有關於指定初始值設定項的一般問題。我有一個類,從那裏我想調用一個初始化程序,但在我開始填充我的@properties傳遞數據我想使數據默認。例如:指定初始值設定項並調用它

-(id)initWithDefault:(NSDictionary*)defaultTemplate 
{ 
    self = [super init]; 

    _fontColor = [defaultTemplate objectForKey:@"color"]; 
    _fontSize = [[defaultTemplate objectForKey:@"size"] intValue]; 

    return self; 
} 

-(id)initWithTemplate:(NSDictionary*)template 
{ 
    self = [self initWithDefault:myDefaultTemplate]; 

    //now i doing something with my template 

    return self; 

} 

這是防止null @properties的一種方法嗎?這是指定初始化程序的正確用法嗎?當然你可以假定myDefaultTemplates不是null,並且在鍵中沒有null對象。

回答

2

這對我來說似乎很好。我會使用安全的方式(下面介紹),但否則你的代碼是好的。

-(id)initWithTemplate:(NSDictionary*)template 
{ 
    if(self = [self initWithDefault:myDefaultTemplate]) { 

     //now i doing something with my template 

    } 

    return self; 

} 
+0

但爲什麼使用這個if()?在這種情況下,我可以使用空屬性? – Kuba

+1

不,檢查初始化程序('initWithDefault:')是否返回一個非零值。如果'self'沒有設置屬性沒有意義 – adig

+0

哦,沒關係。謝謝! – Kuba

0

由於_fontColor和_fontSize變量是屬性的本地變量,因此您的實現非常好。

adig的建議只是對已經實施的內容的增強。當您的對象因任何原因未被分配時,此檢查會照顧到情況。

相關問題