iOS View Controller Lifecycle


After instantiation and outlet-setting, viewDidLoad is called, this is an exceptionally good place to put a lot of setup code.


[super viewDidLoad];//always let super have a chance in lifecycle methods

//do some setup of my MVC

But be careful because the geometry of your view(its bounds) is not set yet!


Just before the view appears on screen, you get notified

(argument is just whether you are appearing instantly or over time via animation)

Your view will only get “loaded” once, but it might appear and disappear a lot. So don’t put something in this method that really wants to be in viewDidLoad. Otherwise, you might be doing something over and over unnecessarily.

Do something here if things you display are changing while your MVC is off-screen.

Summary: This method is for geometry-related initialization, lazy execution and late updating.


You get notified when you will disappear off screen, this is where you put “remember what’s going on” and cleanup code.



[super viewWillDisappear:animated];//call super in all the viewWill/Did... methods

//let's be nice to the user and remember the scroll position they were at...

[self saveDataToPermanentStore];//maybe do in did instead?

//but be careful not to do anything time-consuming here, or app will be sluggish

//maybe even kick off a thread to do what needs doing here


In ios with AutoLayout, you have to do such stuff in viewDidLayoutSubviews (also previously mentioned). viewDidLayoutSubviews is the method sent to you after constraints have been processed.Note that while viewWillAppear: will get called only as you go (back) on screen…

viewDidLayoutSubviews is called every time self.view’s bounds changes (i.e. more ofter). This makes perfect sense when you think about it.

Doing geometry-dependent stuff in viewWillAppear: is an artifact from the days when

a) there was no Autolayout and b) there was no viewDidLayoutSubviews!