What increases an object’s retain count?

You are correct that the retain count is 2 after adding it to an array. However, you should only worry about the retain counts you add to the item explicitly.

Retaining an object is a contract that says “I’m not done with you, don’t go away.” A basic rule of thumb (there are exceptions, but they are usually documented) is that you own the object when you alloc an object, or create a copy. This means you’re given the object with a retain count of 1(not autoreleased). In those two cases, you should release it when you are done. Additionally, if you ever explicitly retain an object, you must release it.

So, to be specific to your example, when you create the Person, you have one retain count on it. You add it to an array (which does whatever with it, you don’t care) and then you’re done with the Person, so you release it:

Person *p = [[Person alloc] init]; //retain 1, for you
[array addObject:p]; //array deals with p however it wants
[p release]; //you're done, so release it

Also, as I said above, you only own the object during alloc or copy generally, so to be consistent with that on the other side of things, you should return the array autoreleased, so that the caller of the getPeople method does not own it.

return [array autorelease];

Edit:
Correct, if you create it, you must release it. If you invest interest in it (through retain) you must release it.

Leave a Comment