Friday, March 25, 2011

Demystifying the viewDidLoad and viewDidUnload methods

The viewDidLoad is called after the controller's view is loaded into memory. The viewDidUnload is called when the controller's view is released from memory. Most of us think of these methods as just two calls that are invoked when the view controller is loaded and unloaded. However the important part of their definition is  the "loaded into memory" and "released from memory" parts. This means that these two functions play a vital role with regards to memory.Usually the viewDidLoad and viewDidUnload functions are called just once and that is the normal  behavior we are all familiar with. However, what we are going to discuss here is about the viewDidLoad and viewDidUnload being called the next time.

The viewDidUnload function will be called in low-memory situations. It is here that the view controller needs to release its views and subviews in order to decrease the memory usage of the application. Then later on the viewDidLoad will be called to recreate the views. So we need to write code in viewDidLoad which are necessary to reinitialize our UI.

What do we need to do?
1. Always make sure you set your outlets to nil in the viewDidUnload method.
eg:- self.myOutlet = nil;
In low-memory situations the xib will be released from memory but doing that alone won't reduce the memory consumption if all the outlets are still retained  in our code. So when we set the outlet to nil, we are invoking the setter function of the outlet which automatically releases it before setting nil to it.

2. Always try to write only UI initialisation code in viewDidLoad. If you write code to alloc/init a variable in your viewDidLoad, then when the method is invoked a second time the variable will be alloc/init'd again causing a memory leak. If you really do need to alloc/init your member variable here, do it only if it is not already allocated.

Note 1: Always set your outlets to nil using the 'self.' prefix otherwise you will only be setting nil to the variable thus causing a memory leak.

Note 2: This is applicable only for those outlets which have been retained using the @property(retain) call which is of course the standard method to handle your outlets.

No comments:

Post a Comment