DevPrep

All topics › IDEs & SDK

UIViewController lifecycle

Junior PRO

Order of calls

  1. init(coder:) / init(nibName:bundle:) / a custom init — the object exists, the view does not yet.
  2. loadView() — called lazily, on the first access to view (not when the controller is created). Loads the view from a storyboard/XIB or creates an empty one; override it to build the root view in code, and then do not call super.loadView().
  3. viewDidLoad() — the view is in memory, outlets are connected. Called once. Add subviews, constraints and subscriptions here. bounds exist but the size is not final (from the storyboard or zero) — do not read geometry here.
  4. viewWillAppear(_:) — the view is about to be added to the hierarchy. Called on every appearance. Suitable for refreshing data that may have changed while the screen was hidden.
  5. viewIsAppearing(_:) (iOS 17, back-deployed to iOS 13) — the view is already in the hierarchy, traitCollection and the parent's geometry are up to date, but the first frame is not drawn yet. Apple recommends it for UI that depends on sizes and traits (instead of viewWillAppear and viewDidLayoutSubviews).
  6. viewWillLayoutSubviews() / viewDidLayoutSubviews() — around the root view's layoutSubviews(); called many times (rotation, keyboard, constraint changes). Manual layout and reading final frames go here.
  7. viewDidAppear(_:) — the screen is shown, the transition animation finished. Start animations, request permissions, focus a field. Starting data loading here is too late — the screen would show up empty; kick it off in viewDidLoad.
  8. viewWillDisappear(_:) — the view is leaving the screen: pop, dismiss, pushing the next controller, switching a tab. Save the draft, stop timers.
  9. viewDidDisappear(_:) — the view has been removed from the hierarchy.
  10. deinit — the controller is released. If it is not called after closing, you have a leak (most often a retain cycle in a closure).

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store