viewDidLoad vs init with ViewControllers

viewDidLoad vs init with ViewControllers

Initializing variables in an iOS application is something you will face every project.
Choosing the right place to init your variables can sometimes be tricky. I recently faced a problem that was difficult to reproduce and changed some variables who were initialized in my viewDidLoad method and for who I couldn't understand that they were changing.

Possible methods to init variables in your viewcontroller are:
- init
- viewDidLoad
- viewWillAppear
- viewDidAppear

To explain my point I started a new project with the template Tab Bar Application. I added logging statements to the viewDidLoad methods in both view controllers. A also added a button to the second view controller who would initialize some images that would give me a memory warning.

After logging some statements and came to the following conclusion:

15:11:40.077 testblog2[4865:707] FirstViewController viewdidload
15:11:56.720 testblog2[4865:707] SecondViewController viewDidLoad
15:12:05.710 testblog2[4865:707] Pressed loading images button
15:12:19.025 testblog2[4865:707] Received memory warning. Level=1
15:12:21.272 testblog2[4865:707] SecondViewController didReceiveMemoryWarning

=> Now changing to the first tab

15:12:30.822 testblog2[4865:707] FirstViewController viewdidload

If you initialize variables in the viewDidLoad method then please keep in mind that these variables could be reinitialized after receiving a memory warning. Cocoa will remove the view and your viewDidLoad method will be triggered again once you go to that specific view controller.