Cocoa 为什么我必须添加这些内存语句?

Cocoa 为什么我必须添加这些内存语句?,cocoa,memory-management,Cocoa,Memory Management,我在运行Aaron Hillegass编写的MacOSX Cocoa编程第8章中的程序时遇到了一个错误。 该程序将tableview绑定到阵列控制器。在阵列控制器的setEmployees方法中 -(void)setEmployees:(NSMutableArray *)a { if(a==employees) return; [a retain];//must add [employees release]; //must add employe

我在运行Aaron Hillegass编写的MacOSX Cocoa编程第8章中的程序时遇到了一个错误。 该程序将tableview绑定到阵列控制器。在阵列控制器的setEmployees方法中

-(void)setEmployees:(NSMutableArray *)a
{
    if(a==employees)
        return;
    [a retain];//must add
    [employees release]; //must add
    employees=a;
}
在这本书中,两个retain和release语句没有包括在内,每当我试图添加新员工时,我的程序就会崩溃。在谷歌搜索之后,我发现这两个必须添加语句以防止程序崩溃。
我不理解这里的内存管理。我将
a
分配给
员工
。如果我没有放弃任何东西,为什么我必须保留
a
?为什么我可以在上次分配声明中使用
员工之前释放员工?

这是使用手动参考计数(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示例代码