【问题标题】:Why must I add these memory statements?为什么我必须添加这些内存语句?
【发布时间】:2012-07-24 09:23:03
【问题描述】:

当我从 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

【问题讨论】:

    标签: cocoa memory-management


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多