iOS memory management - viewDidUnload
I开发者_StackOverflow社区 have a navigation based app. The screen List has a UITableView
with a list of books. The list of books is in a property NSArray
that was built dynamically by executing an HTTP request. When one clicks in one of the rows in the List, one'll navigate to the screen Details. Let's say there is a memory warning at this point. When you come back to the screen List, the NSArray
is nil because viewDidUnload
was called, so the List will be empty.
What is the correct way to handle this situation? Should I not set the NSArray
to nil in viewDidUnload
?
Typically you will only nil out properties for your IBOutlet UI elements. You can also safely clean up anything that you can recreate in -viewDidLoad
. But generally speaking, this method is only for cleaning up and freeing memory related to the view, not the view controller.
The correct way is not to store your data in a UIViewController, but in another object that manages your data.
A viewcontroller serves as a link between your model and your screen. You should not use it to store your data.
Usually I set NS(Mutable)Array of the objects in void dealloc(). Nil and release (if the object is not autoreleased).
If you use uinavigationcontroller, the view is pushed, so when you return from your detail view, normally you will have your previous data, unless you put in viewwillappear a refresh.
My guess is that you have a problem freeing the memory from the http request.
If you array is built in the viewDidLoad section then you can set it to nil. When the view is recalled it will be rebuilt.
Generally you want to set anything to nil in the viewDidUnload that can be rebuilt in either the viewDidLoad section or the xib file.
I would recommend initializing lazily though like this -
- (NSArray *)bookArray {
if (bookArray == nil) {
bookArray = [[NSArray alloc] init];
}
return bookArray;
}
then in the viewDidLoad:
self.bookArray = [NSArray arrayWithOjects:...,nil];
精彩评论