Introduction

The ViewController lifecycle is fundamental to building robust iOS apps. Understanding each stage helps you manage resources, UI updates, and data flow efficiently.

Lifecycle Methods

  • init(coder:)/init(nibName:bundle:) — Initialization
  • loadView() — Create or load the view hierarchy
  • viewDidLoad() — Called after the view is loaded
  • viewWillAppear(_:) — Before the view appears
  • viewDidAppear(_:) — After the view appears
  • viewWillDisappear(_:) — Before the view disappears
  • viewDidDisappear(_:) — After the view disappears
  • deinit — Cleanup

Example

class MyViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("viewDidLoad")
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("viewWillAppear")
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("viewDidAppear")
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        print("viewWillDisappear")
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        print("viewDidDisappear")
    }
    deinit {
        print("deinit")
    }
}

Best Practices

  1. Use viewDidLoad for one-time setup
  2. Use viewWillAppear for UI updates before the view is visible
  3. Use viewDidAppear for animations or data fetching
  4. Use viewWillDisappear to pause tasks or save state
  5. Use deinit for cleanup

Conclusion

Mastering the ViewController lifecycle is key to building efficient, bug-free iOS apps. Use each method appropriately to manage your app's behavior and resources.