2012-07-24 120 views
0

我在Aaron Hillegass的Cocoa Programming for Mac OSX的第8章中運行這個程序時遇到了一個錯誤。 該程序將一個tableview綁定到一個數組控制器。在陣列控制器的setEmployees方法,爲什麼我必須添加這些內存語句?

-(void)setEmployees:(NSMutableArray *)a 
{ 
    if(a==employees) 
     return; 
    [a retain];//must add 
    [employees release]; //must add 
    employees=a; 
} 

在這本書中,兩個保留和釋放語句不包括與我的程序崩潰每當我嘗試添加一個新的員工。谷歌搜索後,我發現這兩個必須添加的語句,以防止程序崩潰。 我不明白這裏的內存管理。我將a分配到employees。如果我沒有釋放任何東西,爲什麼我必須保留a?爲什麼在最後的賦值語句中使用它之前我可以釋放employees

回答

2

這是使用手動引用計數(MRC)的制定者的標準模式。一步一步,這就是它的作用:

-(void)setEmployees:(NSMutableArray *)a 
{ 
    if(a==employees) 
     return;   // The incoming value is the same as the current value, no need to do anything. 
    [a retain];   // Retain the incoming value since we are taking ownership of it 
    [employees release]; // Release the current value since we no longer want ownership of it 
    employees=a;   // Set the pointer to the incoming value 
} 

在自動引用計數(ARC)的訪問可以簡化爲:發行版是爲你做

-(void)setEmployees:(NSMutableArray *)a 
    { 
     if(a==employees) 
      return;   // The incoming value is the same as the current value, no need to do anything. 
     employees=a;   // Set the pointer to the incoming value 
    } 

的保留/。你沒有說過你會遇到什麼樣的崩潰,但似乎你正在MRC項目中使用ARC示例代碼。

+0

你說得對。我使用4.1並沒有ARC。謝謝。 – Standstill 2012-07-24 09:47:37

相關問題