As soon as you give a class a new instance variable (ivar), update the class’s dealloc
method (and viewDidUnload
, if the ivar is an IBOutlet
) to clean up the ivar. Do this before you write the code using the new ivar. Here’s why:
Never Forget
You can’t forget to release
an ivar, if the code that reaps it is in place before the code that creates it. Updating dealloc
first means less memory leaks.
Even with an impossibly good testing protocol, that catches every memory leak, it’s faster to fix memory leaks before they happen than to track them down after the fact.
You Know More Than They Do
Sometimes there’s an important step that must be done when cleaning up an ivar. Maybe you need to set it’s delegate
to nil
, or unregister for a notification, or break a retain cycle. You know this when you setup the ivar. But your coworkers don’t know this a priori. When you checkin code that leaks or triggers an analyzer warning, they’ll want to fix it, and since they know less than you do about your code, they’re more likely to miss a crucial step. (Even if you work alone, remember Future You! In N weeks, Future You will have to deal with all the code Present You wrote today … and they’ll be in the same situation as any other co-worker, because they won’t remember everything Present You knows. )