You release
an object when you no longer have any interest in it. This happens for many reasons; it might be because you've finished with the object, or have passed the control over the object lifetime to another object. It might be because you're about to replace the object with a fresh instance, it might be because you (the owner object) are about to die.
The last one seems to be relevant in your case. You create these object in viewDidLoad
and repeatedly need them (i.e. to add them to cells) until your object is no longer functioning. In this case, just as you create them in viewDidLoad
, you can release them in viewDidUnload
.
Edit: I should really mention autorelease
, but this isn't relevant in this instance. Memory management is best handled with a notion of 'owner' - the person who creates something (or retains it) should be responsible for deleting it (or release
ing in ObjC parlance). autorelease
handle some cases where you need to give an object to an alternate owner, having previously owned it yourself (typically via a method return). If you are the creator, you can't just release
it before returning it to the new owner, as it will be deleted before the new owner has a chance to stake an interest in it. However, you can't just not release
it; it will leak. As such, the system provides a big list of objects that it will release on your behalf at some point in the future. You pass your release
responsibility to this list, then return
the object to the new owner. This list (the autorelease pool) ensures your release will occur at some point, but gives the new owner a chance to claim the object as theirs before it's released.
In your case, you have a clear interest in owning the objects for the lifetime of your view controller - you need to, at any time, be able to add them to view cells in response to a table data reload. You're only done with them when your view controller dies, so the viewDidUnload
(or possibly dealloc
) is the only sensible place to release
them.