Sobes.tech

sobes.tech AI

Answer from AI

The lifecycle of a ViewController in iOS consists of several key stages that manage the loading, displaying, and unloading of the controller:

  1. Initialization — creating an instance of the ViewController.
  2. loadView() — called to create and set up the controller's root view if it is not loaded from a storyboard.
  3. viewDidLoad() — called after the view has been loaded into memory; here, the interface is usually configured, and data is initialized.
  4. viewWillAppear(_:) — called before the view appears on the screen; you can update data or the interface.
  5. viewDidAppear(_:) — called after the view appears; here, you can start animations or load data.
  6. viewWillDisappear(_:) — called before the view is hidden; you can save state.
  7. viewDidDisappear(_:) — called after the view is hidden; you can stop processes.
  8. deinit — resource cleanup when the controller is deallocated.

Example of using lifecycle methods:

class MyViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("View loaded")
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("View will appear")
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        print("View disappeared")
    }
}