R – IPhone – Which View Controller methods to use

cocoa-touchdesign-patternsiphoneuiviewcontroller

I'm trying to figure out what logic should go into the different UIViewController methods like viewDidLoad, viewDidAppear, viewWillAppear, …

The structure of my app is that I have a root view controller that doesn't really have a view of its own, rather it has a tab view controller and loads other view controllers into it. But in the future, it may have to load other view controllers instead of the tab bar controller depending on app logic.

My main question is, what do people usually put into the viewDidLoad, …. methods.

Currently I:

viewDidLoad – setup the tab bar controller and set its view to the view controller's own view

viewDidAppear – check if user has stored login info
if not – present with login
if so, login and get app data for first tab

I'm trying to figure out now if my logic for setting up my tab bar controller should go into loadView rather than viewDidLoad.

Any help would be great. Small examples found on the web are great, but they don't go into detail on how larger apps should be structured.

Best Answer

You should not implement both -viewDidLoad and -loadView; they are for different purposes. If you load a NIB, you should implement -viewDidLoad to perform any functions that need to be done after loading the NIB. Wiring up the tabbar is appropriate there if you haven't already done it in the NIB.

-loadView should be implemented if you do not use a NIB, and should construct the view.

-viewWillAppear is called immediately before you come onscreen. This is a good place to set up notification observations, update your data based on model classes that have changed since you were last on screen, and otherwise get your act together before the user sees you. You should not perform any animations here. You're not on the screen; you can't animate. I see a lot of animation glitches due to this mistake. It kind of works, but it looks weird.

-viewDidAppear is called after you come onscreen. This is where you do any entry animations (sliding up a modal, for instance; not that you should do that very often, but I was just looking at some code that did).

-viewWillDisappear is called right before you go offscreen. This is where you can do any leaving animations (including unselecting tableview cells and the like).

-viewDidDisappar is called after you're offscreen (and the animations have finished). Tear down any observations here, free up memory if possible, go to sleep as best you can.

I touch on setting up and tearing down observations here. I go into that in more depth in View controllers and notifications.