Search code examples
iphoneiosviewdidloadviewwillappear

When to put into viewWillAppear and when to put into viewDidLoad?


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?


Solution

  • 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.