2011-01-23 57 views
0

我有一個同步的函數,但似乎無法直接更改該塊中實例變量的值。在目標C中設置同步塊中的實例變量C

+(id)allocWithZone:(NSZone *)zone 
{ 
@synchronized(self) { 
    if (sharedInstance == nil) { 
     sharedInstance = [super allocWithZone:zone]; 

     //This is not allowed 
     something = @"hello"; 

     //This is allowed 
     self.something = @"hello world!"; 

     return sharedInstance; 
    } 
} 

return nil; 
} 

爲什麼會出現這種情況?我有一個需要直接訪問的變量(我不想綜合該變量)。我如何解決這個問題?

+0

你是什麼意思,「不允許」?該代碼是否不能編譯?觸發運行時錯誤?如果崩潰,你能提供崩潰的具體細節嗎? – Tim 2011-01-23 08:06:41

+0

@Darren有很多錯誤,首先是他正在像一個實例方法那樣處理一個類方法,並試圖在調用`-init`之前設置ivars。 – 2011-01-23 08:12:55

回答

5

您不能更改實例變量,因爲這不是實例方法。實際上,self的價值本身就是這個類。您的代碼行self.something = @"hello world!"也不起作用。你真正想要的是sharedInstance.something = @"hello world!",那只有在something是屬性的情況下才會起作用。更好的辦法是在init方法中設置ivars。

哦,你沒有商業設置ivars在+allocWithZone:無論如何。該對象尚未初始化。

假設你正在嘗試在這裏創建一個singleton(就像它看起來那樣),你可能需要在Obj-C的單例中讀這個blog post