ViewController Lifecycle


  • Just like we humans are born and we eventually die, so do ViewControllers. ViewControllers have a lifecycle with certain key moments that we can tap into and we can write code to specify what should happen in those moments.

viewDidLoad()

  • The first thing that happens
  • All the IBOutlets, IBActions, all of the view related objects get connected up and is now accessible.

Important: viewDidLoad( ) only gets called ONCE, when the view is created.

viewWillAppear()

  • Called right after viewDidLoad()

  • This is called just before the view actually shows up on the screen.

  • The user is not yet able to see anything, but it is, however, a good time point to be able to hide or show certain UI components.

    ex. hiding the navigation bar

  • The user is not yet able to detect any changes in the view.

viewDidAppear()

  • Here is where the user is able to actually see things on the screen.
  • At this point, when you tap into this method, then the view is already on screen and the user is already able to see the ViewController.
  • A good time point to, for example, start a countdown timer, or start an animation.

viewWillDisappear()

  • User may tap into this method when the user might navigate back or if they somehow dismissed the current ViewController.

  • Here, we write some code to prepare for ViewController dismissals.

    ex. stopping animations

viewDidDisappear()

  • The view is already off the screen.
  • The last moment where we get to change anything about that previous view before it disappears off the screen.

Important: Just because the view has disappeared, it doesn't mean that it has been deallocated or deleted from the memory of the phone.

→ viewDidDisappear literally means that the user can't see it.

  • If a certain ViewController is presented modally (where the second VC doesn't cover the entire screen), the previous ViewController's viewWillDisappear( ) and viewDidDisappear( ) method will NOT be called.

  • If we look closely, the order of which method gets called may not seem just as we expected.

Q. Why can't we assign IBOutlet values in a prepare( ) method for a segue?

→ The above code doesn't work.

→ At the time we are trying to set label.text, the label of the second VC is still not created (=nil).

Remember we said that a ViewController's IBOutlet, IBActions all get connected up when viewDidLoad( ) is called.

→ But since the label of the secondVC appears to be nil, we can infer that the time when prepare( ) is called is before the viewDidLoad( ) of the secondVC is called.

profile
맛있는 iOS 프로그래밍

0개의 댓글