When to put into viewWillAppear and when to put into viewDidLoad?
Asked Answered
G

2

5

I get used to put either of viewWillAppear and viewDidLoad, it's OK until know. However I'm thinking there should be some rules that guide when to put into viewWillAppear and when to put into viewDidLoad?

Guillemot answered 23/1, 2013 at 4:7 Comment(0)
A
12

Simple rule I use is this. viewDidLoad is when the view's resources are loaded. The view is not drawn onscreen yet. So calculations and code dealing with the geometry and visuals of the view should not be put here. They should be in the viewWillAppear or viewDidAppear method.

Also viewWillAppear can be called multiple times

  1. When a popover/modal view is displayed and remove
  2. When an alert view/actionsheet/uiactivityController's view is displayed and removed.

For these reason, viewWillAppear should not contain codes that takes longer to finish. (at least the code running on the main thread). Neither should codes that only needs to be run once per view display.

There are more I am sure but these are simple to remember and I hope it helps.

Applicative answered 23/1, 2013 at 4:14 Comment(0)
G
3

viewDidLoad: Alerts you that a view has finished loading

viewWillAppear: Runs just before the view loads

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.

Gathers answered 23/1, 2013 at 4:46 Comment(1)
good explanation, just that i've read it before over here: #1580050Selenography

© 2022 - 2024 — McMap. All rights reserved.