When the user switches to another program and then back again., the original program’s view will be replaced by a new view from another program. So when the user switches back to the original program, would viewDidLoad be called the second time ?
Am asking this because if this is the case, then the initialization code placed inside viewDidLoad would be executed every time the user switches the screen back and forth. And this could result in reseting views and loosing unfinished works of the user …
Don’t do view controller initialisation in
viewDidLoad. This is a common mistake.For stuff that should only happen once when the view controller is loaded, do it in the controller’s init method, like this:
The
initWithNibName:bundle:method is called before the view is loaded from the nib, and is only called once in the lifespan of the view controller.The controller’s view can be loaded and unloaded multiple times during the lifespan of the controller and
viewDidLoadwill be called every time. It may be unloaded whenever it’s not on screen, usually if memory is low.If you do set stuff up in
viewDidLoad(e.g. adding subviews programmatically) you should always unset them again inviewDidUnload.Think of
viewDidLoadandviewDidUnloadas being like the init/dealloc for the view property of the view controller. For stuff that relates to the views, create and release it in those methods. For stuff that relates to the controller itself, create and release it ininitWithNibNameanddealloc.UPDATE: On iOS 6 and later,
viewDidUnloadis never called any more (unless the view is explicitly set to nil in the code), and soviewDidLoadwill typically only be called once in the life of a view controller. This makes the advice above less critical, but it’s still best practice, and still necessary if you need to support iOS 5 and earlier.UPDATE 2: If you are loading your view controller from a Storyboard (which is now the recommended practice) instead of creating it programmatically then
initWithNibName:bundle:will not be called. UseinitWithCoder:orawakeFromNibto initialize your controller instead.