TheAtlantaGoat TheAtlantaGoat -4 years ago 131
iOS Question

Why does Apple recommend us to not invoke viewWillLoad, viewWillAppear, viewDidDisappear, etc.?

I'm following an exercise from a book and we're building out the view controllers programatically and creating unit tests. The book also says this and from previous experience reading Apple reference docs, Apple references always says not to invoke viewDidLoad, viewWillAppear, viewDidDisappear, etc directly. I'm curious to know why is this and what happens if we do?

Answer Source

viewDidLoad, viewWillAppear, viewDidDisappear and so on are the runtime's way of letting you know that certain important things are happening:

  • viewDidLoad, the view controller has just obtained its view

  • viewWillAppear, the view controller's view is about to be placed into the interface

  • viewDidDisappear, the view controller's view is about to be removed from the interface

These are events that the runtime is responsible for, and it sends you messages to let you know they are happening so that you can respond, if you wish, at the appropriate moment.

It would make no sense for you to call them, because you do not know when these things are happening (except insofar as the runtime calls them)! If you called them at some arbitrary moment, you would be lying, e.g. saying that the view has just loaded when in fact it has not just loaded, and so you would break your own code or worse.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download