gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:41:41 24 4
gpt4 key购买 nike

当我运行 Aaron Hillegass 所著的《Mac OSX Cocoa 编程》第 8 章中的程序时,遇到错误。该程序将 TableView 绑定(bind)到数组 Controller 。在数组 Controller 的setEmployees方法中,

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

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

最佳答案

这是使用手动引用计数 (MRC) 的 setter 的标准模式。一步一步,这就是它的作用:

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

关于cocoa - 为什么我必须添加这些内存语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11627833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com