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;
}

书中没有包含两个保留和释放语句,每当我尝试添加新员工时,我的程序就会崩溃。谷歌搜索后,我发现这两个必须添加的语句以防止程序崩溃。我不明白这里的内存管理。我分配aemployees. a如果我不释放任何东西,为什么我必须保留?为什么我可以employees在最后一个赋值语句中使用它之前释放它?

4

1 回答 1

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 示例代码。

于 2012-07-24T09:33:26.567 回答