2012-07-24 69 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

相关问题