Let's check out that snippet of code keeping the Cocoa Memory Management rules in mind. I'm going to modify it slightly:
for (int i=0; i < [list count]; i++)
{
id anObject = [list objectAtIndex(i)] ;
[anObject release];
}
This is just so I can talk about anObject
, otherwise it is identical to your code.
Now, you obtained anObject by sending objectAtIndex: to an array. Here is the relevant quote from the rules:
You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.
- Does objectAtIndex: start with alloc? No.
- Does objectAtIndex: start with new? No.
- Does objectAtIndex: contain copy? No.
- Did you retain anObject? No.
Therefore, the last bolded sentence applies.
You must not release anObject. The release in the code is incorrect.
I've written the above out at some length not to try to slap you down and make you look stupid, but because I used to find this stuff just as confusing as you do and the only way I could stop my code from leaking or crashing was by mentally ticking off the answers to those four questions pretty much for every object I used. It doesn't take long for it to become second nature such that you can glance at a piece of code and instantaneously figure out what needs releasing.