谁在复制时负责释放数组的对象
问题说明
在Objective-C中,如果array1使用mutableCopy复制到array2上,并假设代码在main()中完成,谁负责释放数组中包含的对象?它是main()还是array2?
In Objective-C, if array1 is copied onto array2 using mutableCopy, and suppose the code is done in main(), who is responsible for releasing the objects contained in the array? Is it main() or array2?
正确答案
我认为以前的答案错过了点,否则asker很不清楚。实际的问题不是数组,而是数组内容:
I think the previous answers have missed the point, or else the asker was pretty unclear. The actual question isn't talking about either array, but rather the array contents:
谁负责释放在数组中?是main()还是array2?
who is responsible for releasing the objects contained in the array? Is it main() or array2?
两个 array1
array2
负责发布对象。
Both array1
and array2
are responsible for releasing the objects.
从 NSArray文档:
数组保持对其内容的强引用 - 在托管内存环境中,每个对象在将其ID添加到数组之前接收到一个保留消息,并在从数组中删除时发布一条释放消息;当数组被释放时。
"Arrays maintain strong references to their contents—in a managed memory environment, each object receives a retain message before its id is added to the array and a release message when it is removed from the array or when the array is deallocated."
首先,每个对象都由NSArray array1
。当你通过 -mutableCopy
创建 array2
时,你会得到一个NSMutableArray指向相同的对象,再次。如果你现在要释放 array1
,当它的 dealloc
方法被调用时,它将释放每个对象包含。但是, array2
保留了它们,所以对象不会被销毁 - 只有当它们的保留计数达到0时,如果 array2
被销毁,没有其他人保留任何对象(或者从
array2
中删除)。
To begin with, each of the objects are retained by the NSArray array1
. When you create array2
via -mutableCopy
, you get an NSMutableArray which points to the same objects, and retains each of them again. If you were to release array1
at this point, when its dealloc
method were called it would release each of the objects it contains. However, array2
has retained them, so the objects won't be destroyed — only when their retain count reaches 0, which would happen if array2
were destroyed and nobody else has retained any of the objects (or when they are removed from array2
).
由于集合类(数组,集合,字典等)处理保留和释放它们的内容,所以你需要担心的是保留或释放集合本身。由于你使用了 -mutableCopy
,记住你已隐式保留 array2
,所以你应该在完成后与它。
Since collection classes (arrays, sets, dictionaries, etc.) handle retaining and releasing their contents, all you have to worry about is retaining or releasing the collection itself. Since you used -mutableCopy
, remember that you have implicitly retained array2
, so you should release it when you're done with it.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcakikh
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20