View Controller Lifetime Events

As views come and go, driven by view controllers and the actions of the user, events arrive that give your view controller the opportunity to respond to the various stages of its existence. By overriding these methods, your UIViewController subclass can perform appropriate tasks. Most commonly, you’ll override viewWillAppear:, viewDidAppear:, viewWillDisappear:, or viewDidDisappear:. Note that you must call super in your override of any of these four methods.

Let’s take the case of a UIViewController pushed onto the stack of a navigation controller. It receives, in this order, the following messages:

  • willMoveToParentViewController:
  • viewWillAppear:
  • updateViewConstraints
  • viewWillLayoutSubviews
  • viewDidLayoutSubviews
  • viewDidAppear:
  • didMoveToParentViewController:

When this same UIViewController is popped off the stack of the navigation controller, it receives, in this order, the following messages:

  • willMoveToParentViewController: (with argument nil)
  • viewWillDisappear:
  • viewDidDisappear:
  • didMoveToParentViewController: (with argument nil)

In these names, the notions “appear” and “disappear” reflect the view’s insertion into and removal from the interface. A view that has appeared (or has not yet disappeared) is in the window; it is part of your app’s active view hierarchy. A view that has disappeared (or has not yet appeared) is not.

Disappearance can happen because the UIViewController itself is taken out of commission, but it can also happen because ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.