Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What works in viewDidUnload should be moved to didReceiveMemoryWarning?

In new iOS 6, viewDidUnload is deprecated and we have been instructed to use didReceiveMemoryWarning instead, to manage objects in UIViewController instances and subclasses. Is it equally effective to assign nils to UIView kinds inside didReceiveMemoryWarning like the way it has been done inside viewDidUnload?

I am asking this because these two methods seems to be working differently. It seems like didReceiveMemoryWarning doesn't guarantee viewDidLoad to be called again to re-instantiate any necessary UIViews.

I suspect with iOS 6, memory management is done without requiring to manually deallocate UIView. Please help me to know what I have missed in understanding the lifecycle of UIViewController.

like image 639
petershine Avatar asked Oct 03 '12 12:10

petershine


2 Answers

My preferred method is now the following:

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if (self.isViewLoaded && !self.view.window) {
        self.view = nil;
    }
    // Do additional cleanup if necessary
}

Note that the test self.isViewLoaded is essential, as otherwise accessing the view causes it to load - even the WWDC videos tend to miss that.

If your other references to subviews are weak references, you don't have to nil them out here, otherwise you want to set them to nil, too.

You should get rid of viewDidUnload completely, and every code there should move to appropriate places. It wasn't guaranteed to be called prior to iOS 6 before anyway.

like image 54
Eiko Avatar answered Nov 11 '22 01:11

Eiko


In the iOS reference for viewDidUnload:, it states that this is deprecated for iOS 6 because

Views are no longer purged under low-memory conditions and so this method is never called

It doesn't say anything about placing this code in didReceiveMemoryWarning:. Since views are no longer purged under low memory conditions, you never have to worry about cleaning up your views in either method.

like image 24
Phil Avatar answered Nov 11 '22 00:11

Phil