-2

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

Laurence Wingo
  • 3,912
  • 7
  • 33
  • 61
  • 3
    Read the documentation for those methods. Read about a view controller's lifecycle. They are called by the framework. They are not meant to be called directly. – rmaddy Feb 27 '17 at 04:45
  • 3
    It's not a recommendation. It's a law. – matt Feb 27 '17 at 04:53
  • 1
    There is a theory which states that if ever anyone invokes viewWillAppear directly, the Universe will instantly disappear and be replaced by something even more bizarre and inexplicable. – T. Benjamin Larsen Feb 27 '17 at 05:14
  • @T.BenjaminLarsen I see, one of those don't ask don't tell type of questions. I'm still curious about this and want to try it out but if it'll crash my computer or end the universe then I will abide. I do sometimes feel like Mr. Burns from the Simpsons and would like to "release the hounds" if no one can explain what happens in this black hole. – Laurence Wingo Feb 27 '17 at 15:52

1 Answers1

4

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141