2013-08-23

Nil Out Views in iOS

Before iOS 6, iOS would take the liberty of deleting any view controller’s view not currently on screen upon a low memory situation. As of iOS 6, Apple decided it would remove the memory-intensive backing stores of the graphical display, and thereby free up some memory, without bothering the app developer. So from the app developer’s point of view, the view remains intact. In actuality, iOS recreates the graphical backing stores when the affected view re-appears. Now iOS 6 no longer invokes either method you may have implemented: viewWillUnload & viewDidUnload.

You can recreate the old behavior. As always, your view controller receives a message about low memory by having its didReceiveMemoryWarning method invoked. You may nil out the controller's view. Be sure to check first that the view is not currently on screen. As always, the  didReceiveMemoryWarning invocation is an opportunity for you to clear unnecessary collections and to close other memory-intensive resources, all in an effort to free up memory.

When the view returns to the screen, you must of course recreate the view and restore the needed resources. Do so in your implementations of the loadView or viewDidLoad methods.

Example code:
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // While off-screen, dispose of the controller's view as well as any memory-intensive variables, collections, and resources that can be recreated. 

    NSLog(@"TRACE - %s:%d someObject=%@", __func__, __LINE__, self);  // If you want to log this for educational purposes.
    if( [self.view window] == nil ) { // Verify view is not on-screen.
        [myCollection removeAllObjects]; // Clear a collection.
        self.myImageView = nil; // Clear a resource.
        self.view = nil; // Re-creating pre-iOS 6 behavior to clear view.
    }

No comments:

Post a Comment