Have a peek at the documentation for didReceiveMemoryWarning:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html
Note开发者_运维问答 how it says, and I quote:
In iOS 3.0 and later, if your view controller holds references to objects in the view hierarchy, you should release those references in the viewDidUnload method instead. In earlier versions of iOS, you should continue to release them from this method.
Why is this the case? What changed in iOS 3.0 that made it so that view-hierarchy views must not be cleaned up directly in didReceiveMemoryWarning? I can't imagine what could possibly make that dangerous or bad.
Any ideas guys?
In iOS 3.0 viewDidUnload
and viewDidLoad
were introduced.
If you look at their description, you'll see that:
viewDidLoad called after the view controller has loaded its associated views into memory. This method is called regardless of whether the views were stored in a nib file or created programmatically in the loadView method.
This means that, both when your view is loaded from a Nib, or when you create it programmatically (and the framework calls for you at the right moment loadView
), you have a single point where you can access your new view and complete its initialization, like adding subviews, or whatever you need.
The counterpart to viewDidLoad
is viewDidUnload
that you can override like this:
-(void)viewDidUnload {
<do all the necessary clean up>
[super viewDidUnload];
}
so, you have one single point for clean-up, and you don't need to do any specific clean-up in didReceiveMemoryWarning
, because viewDidUnload
is called whenever a view is deallocated, i.e., also when it is deallocated due to didReceiveMemoryWarning
.
This is different to what happened previously to iOS 3.0, where you had to come out with your own scheme for completing initialization and clean-up with no support from the framework, i.e. when didReceiveMemoryWarning
caused a view to be deallocated, your clean-up method was not automatically called and you had to duplicate your clean-up code (and explicitly do the clean-up in didReceiveMemoryWarning
).
精彩评论