Junior — Middle
Explain the stages of the lifecycle of a ViewController instance in an iOS application.
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:
- Initialization — creating an instance of the ViewController.
- loadView() — called to create and set up the controller's root view if it is not loaded from a storyboard.
- viewDidLoad() — called after the view has been loaded into memory; here, the interface is usually configured, and data is initialized.
- viewWillAppear(_:) — called before the view appears on the screen; you can update data or the interface.
- viewDidAppear(_:) — called after the view appears; here, you can start animations or load data.
- viewWillDisappear(_:) — called before the view is hidden; you can save state.
- viewDidDisappear(_:) — called after the view is hidden; you can stop processes.
- 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")
}
}