谁在复制时负责释放数组中的对象? [英] Who is responsible for releasing objects in an array when copying?

查看:131
本文介绍了谁在复制时负责释放数组中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于谁在复制时负责释放数组中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆