iPhone App Development: Understanding View Controller Methods
iPhone Application Developers struggle with knowing what view controller methods to use, and when. Picking the wrong method to refresh your user interface can result in an iPhone app that disappoints the users.
To understand when to do something in the UIKit framework, you need to know when messages are sent, especially to view controllers. View controllers have a life cycle just as applications do, and certain messages are sent as views that are displayed and hidden.
The two methods you need to know about in order to work with views are
The following table summarizes what you should do in which method:
|Method||When to Send It||What to Use It For|
|viewDidLoad||After the view controller has loaded its associated views into
|Perform additional view initialization on views loaded
from the storyboard or nib file. For example, if you are displaying
some static text, load that text here.
|viewWillAppear:||When the view is about to become visible||Do the things that are necessary to present the view.
For example, if you are displaying the location of the nearest book
store that carries iPhone Application Development For
Dummies, update that information in this method.
The viewDidLoad message is sent to the view controller after the view controller has loaded its associated views into memory. This method is used to perform view initialization and is not necessarily called every time the view appears. If, for example, the user makes a selection in the view that causes a new view controller to load and slide its view into place, and the user then taps the Back button, this message is not sent when the originating view reappears. That is the job of viewWillAppear:.
The viewWillAppear: message is sent when the view is about to become visible. The first time it is sent is after the viewDidLoad message and then whenever the view reappears, such as when you tap the Back button, for example. You use this method to refresh your user interface, if needed, but not for initialization.