开发者

Iphone: Where to release objects?

where i should release objects: in method dealloc or viewDidUnload?

开发者_StackOverflow

Thanks


The correct way is to release them and set them to nil in both of those methods.

  1. You need to release your objects in viewDidUnload since memory warnings can happen, and if your view doesn't have a superview then you should release your outlets to save memory. The framework will issue a viewDidLoad again if the view was unloaded.
  2. You need to release your objects in dealloc, since viewDidLoad + viewDidUnload is not necessarily called.

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.


A short answer for you question: dealloc()

A long and more complicated answer for your question: both

  1. release any unused IBOutlets in viewDidUnload(). This method will be called when your device is running out of memory.
  2. release any objects that the current view controller is responsible for memory management, and release them in dealloc(). (An autoreleased object doesn't belong to this category)


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];
}


dealloc this way if the parent object is released the child objects will be released as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜