• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

谁在复制时负责释放数组的对象

用户头像
it1352
帮助1

问题说明

在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?

正确答案

#1

我认为以前的答案错过了点,否则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
系列文章
更多 icon
同类精品
更多 icon
继续加载