Does a collection send a -release message to all objects it holds, if I send it an -release?

Does a collection send a -release message to all objects it holds, if I send it an -release?

霞映澄塘 发布于 2021-11-30 字数 731 浏览 859 回复 2 原文

I've been reading that if an collection "gets released" it releases all it's objects as well. On the other hand, I was also reading that a collection would release it's objects as soon as the collection gets deallocated.

But the last thing may not always happen, as apple says. The system decides if it's good to deallocate or not. In most cases it will, but in some cases not.

So I am wondering if a collection can cause memory leaks like this?
And when it does -release all it's objects upon an -release message to the collection itself, then it should actually -retain all objects inside the collection as soon as I -retain the collection itself.

Help me to get a clear picture about that. Thanks!

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



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


長街聽風 2022-06-07 2 楼

Sending an object a release drops its retention count. When its retention count hits zero, it's destroyed. When a container is destroyed (not released), it's objects are released (but if their retention count is non-zero for other reasons, not destroyed).

Short answer: This will all work the way you're expecting, your problem is that you're viewing "released" as meaning "destroyed." They're different.

羞稚 2022-06-07 1 楼

When you add an object to a collection, it's retained by the collection until it's removed or the collection is deallocated. Subsequent retain or release messages sent to the collection don't change the retain count of objects inside the collection.

In other words, think of it in terms of ownership, rather than counting retains.