I tend to release my stuff in -dealloc, and now iPhone OS 3.0 introduced this funny -viewDidUnload method, where they say:
// Release any retained subviews of
the main view. // e.g. self.myOutlet
= nil;
So -viewDidUnload seems to get called when the view of the view controller has been kicked off from memory. And if I have subviews attached to the main view of the view controller, I have to release that stuff only HERE, but not in -dealloc as well?
That's confusing. Also, what if -dealloc causes the view to be unloaded (released)? Then again, it will call -viewDidUnload?
I do realize the difference, that -viewDidUnload is just for the case where the view itself gets killed, but the view controller stays in memory. And -dealloc is for the case where the whole thing goes to trash.
Maybe someone can clear up the confusion.
Best Answer
The intent here is to "balance out" your subview management. Anything that you create in
viewDidLoad
should be released inviewDidUnload
. This makes it easier to keep track of what should be released where. In most cases, yourdealloc
method is a mirror-image of yourinit
method, and yourviewDidUnload
will be a mirror image of yourviewDidLoad
method.As you pointed out, the
viewDid
... methods are to be used when the view itself is loaded and unloaded. This permits a usage pattern in which the view controller remains loaded in memory, but the view itself can be loaded and unloaded as required:Of course, it doesn't hurt to release things in your
dealloc
method as well, as long as you set them tonil
when you release them inviewDidUnload
.The following quote from the Memory Management section of Apple's
UIViewController
documentation, describes it in more detail: