views:

162

answers:

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!

+8  A: 

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.

Marc Charbonneau
Word of God on memory management: http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/MemoryMgmt/index.html
Chuck
+4  A: 

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.

Steven Fisher