添加到数组后保留计数会增加吗?

发布于 2024-11-01 10:11:31 字数 80 浏览 5 评论 0原文

我只是想知道:如果将对象添加到 Objective-C 中的数组或字典中,其保留计数是否会增加?我可以在将特定对象添加到数组或字典后立即释放它吗?

I just wanted to know: will the retain count of an object be incremented if it is added to an array or dictionary in Objective-C? Can I release a particular object immediately after adding it to an array or dictionary?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

潜移默化 2024-11-08 10:11:31

是的,它会增加您添加的对象的保留计数,这就是为什么您可以在将对象添加到数组后立即释放该对象。

NSObject obj1;
obj1=[[NSObject alloc] init];
//obj1's retain count is 1 here.

[array1 addobject:obj1];
//obj1's retain count incremented by 1, so the total retain count is 2.

[obj1 release];
//obj1's retain count decremented by 1, so the total retain count is 1.

array1 将保留该对象,直到 array1 本身未被释放。

Yes, it will increase the retain count of the object you added, that is why you can release the object immediately after adding it to the array.

NSObject obj1;
obj1=[[NSObject alloc] init];
//obj1's retain count is 1 here.

[array1 addobject:obj1];
//obj1's retain count incremented by 1, so the total retain count is 2.

[obj1 release];
//obj1's retain count decremented by 1, so the total retain count is 1.

array1 will keep the object until the array1 itself is not released.

So要识趣 2024-11-08 10:11:31

Hariprasad,

NS[此处的集合名称]保留添加到其中的对象,如 NSResponder 所指出的。其他一些事实:

  1. 对于您的评论“我可以发布它吗?
    添加后”,简短的答案是
    是的。很多时候我会做一个
    autorelease 对于对象
    限制在一个
    集合中,并且在集合之外不需要。
  2. 当您删除一个
    集合中的对象,
    引用计数递减。如果
    你想确保它不会
    从内存中删除(下一个池
    扫)你需要保留
    目的。

Hariprasad,

NS[collection name here] retain objects added to them as NSResponder noted. A few other facts:

  1. To your comment "can I release it
    after adding", the short answer is
    yes. Often times I do an
    autorelease for objects that are
    bound for containment in a
    collection and won't be needed outside the collection.
  2. When you remove an
    object from a collection, the
    reference count is decremented. If
    you want to ensure it won't be
    deleted from memory (next pool
    sweep) you need to retain the
    object.
流绪微梦 2024-11-08 10:11:31

NSArray 保留添加到其中的任何对象。

NSArrays retain any object added to them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文