Reputation: 5830
where i should release objects: in method dealloc or viewDidUnload?
Thanks
Upvotes: 2
Views: 259
Reputation: 36762
Any objects allocated and/or retained as part of loadView
and/or viewDidLoad
should be released in viewDidUnload
. Releasing anything you alloc in viewDidLoad
is easy to grasp, loadView
is a bit harder if you are using a NIB. Any IBOutlet
that is a property defined as retain
will be implicitly retained as part of loadView
.
If the view have for example a subview that is a UITextField
and you connect this view to a property defined as:
@property(nonatomic, retain) IBOutlet UITextField* nameField;
Then the actual text field when loaded from the NIB will have a retain count of +2. +1 because of it's parent view, and +1 because of the property you connected it too. Thus it's memory is not freed until the view controller is released, or the NIB is loaded again.
Unfortunately viewDidUnload
is not called when a view controller is deallocated. So you must explicitly release all your `IBOutlets here as well. I use this patter in order to not forget to release anything:
-(void)releaseOutlets {
// Set all outlets to nil
}
-(void)viewDidUnload {
[self releaseOutlets];
[super viewDidUnload];
}
-(void)dealloc {
[self releaseOutlets];
// Release anything else.
[super dealloc];
}
Upvotes: 1
Reputation: 3236
The correct way is to release them and set them to nil in both of those methods.
Finally you need to set your variables to nil in both of the methods, to not be able to call release on them the second time.
Upvotes: 2
Reputation: 6448
A short answer for you question: dealloc()
A long and more complicated answer for your question: both
Upvotes: 2
Reputation: 3965
dealloc this way if the parent object is released the child objects will be released as well.
Upvotes: 0