Is this the correct (best?) way to release views retained in viewDidLoad, in iOS 4.x or lower? Is there anything else to consider?
- (void) viewDidUnload
{
[super viewDidUnload];
[self releaseViews];
}
- (void) dealloc {
[self releaseViews];
[super dealloc];
}
#define SAFE_RELEASE(a) [a release]; a = nil;
- (void) releaseViews {
SAFE_RELEASE(myView1);
SAFE_RELEASE(myView2);
SAFE_RELEASE(myView3);
}
The
-deallocis correct and the-viewDidUnloadwill work, but typically retained views are only nilled in-viewDidUnloadand not released. This seems to be Apple’s practice as well and it is what they’ve baked into the Xcode when you create an auto-generated IBOutlet via the Assistant editor.For auto-generated IBOutlets, the auto-generated
-viewDidUnloadlooks like this:Also, from the Apple docs on
-viewDidUnload:So, there you go. If your outlet has a property associated with it (which they all should anymore), then nil it in
-viewDidUnload— but don’t release it. This makes sense when you consider what is actually happening in a synthesized accessor; the code looks something like this:As you can see, setting a synthesize property to nil implicitly releases the retained object.
Also from the docs in regards to
-dealloc:Unless you are supporting iOS2.x, there is no need to set objects to nil in dealloc.
So, to summarize Apple’s docs regarding
-viewDidUnloadand-dealloc:-viewDidUnload, nil properties (including IBOutlet properties), but don’t release them-deallocrelease properties, but don’t nil them (unless building for 2.x).