iPhone Method Questions (dealloc an viewDidUnload)
I have been working on an app, and the book I read said to put these statements into the viewDidUnload and dealloc methods. What other information should go here? I have buttons and labels in my program. Do I need to do anything for them?
I want an efficiently running application.
Here's my code:
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.doublePicker = nil;
self.color = nil;
self.choice = nil;
[super viewDidUnload];
}
- (void)dealloc {
[doublePic开发者_如何学Goker release];
[color release];
[choice release];
[super dealloc];
}
You should only release your IBOutlets and other UI elements in viewDidUnload. All the other data that you allocated in your view controller (as well as the IBOutlets) should be released in the dealloc method. That's because the view can be loaded and unloaded multiple times during the lifetime of a view controller. For example, a view can be unloaded if it is not visible, but the data behind it (in the view controller) still needs to be kept in memory. When both the view and its controller are no longer needed, the dealloc method is called.
The code you posted is correct, but you should also create properties for your outlets, like so:
in your .h file:
@property (nonatomic, retain) UIPickerView *doublePicker;
@property (nonatomic, retain) UIPickerView *color;
// ...etc
in your .m file:
@synthesize doublePicker;
@synthesize color;
// ...etc
There is some debate about this technique (explicitly retaining your outlets and releasing them like this), but it is the technique that Apple recommends:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmNibObjects.html#//apple_ref/doc/uid/TP40004998-SW2
The general rule is that you want to call release
on anything that you alloc
or init
. Components that you create in xib's do not need to be released.
精彩评论