views:

2394

answers:

1

I have always been a bit unclear on the type of tasks that should be assigned to viewDidLoad vs. viewWillAppear: in a UIViewController subclass. For example, I am doing an app where I have a UIViewController subclass hitting a server, getting data, feeding it to a view and then displaying that view. What are the pros and cons of doing this in viewDidLoad vs. viewWillAppear?

Thanks in advance.

Cheers, Doug

+11  A: 

viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.

However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.

Hope that helped you a bit,

Leon

LeonBrussels
So, regarding viewWillAppear potentially being called repeatedly. Would that method fire if, for example, the viewcontrollers view became visible after having been hidden (I mean occluded here, not the hidden method on UIView). In what scenerio would viewWillAppear be called without being preceded by a call to viewDidLoad?
dugla
viewDidLoad ONLY gets called when the view is constructed - so for example after a view controller initFromNibNamed call when the view is accessed.viewWillAppear is called anytime your view controller was not in view but comes into view - so when your view controller is pushed, viewWillAppear is called. If you push another subview from there, and the user returns, viewWillAppear is called again.
Kendall Helmstetter Gelner
Thanks Kendall. Yah, a few strategically placed NSLogs got me sorted. viewWillAppear/viewWillDissappear fire on viewcontroller push/pops.
dugla