UIViewController lifecycle explained

UIViewController Lifecycle

In this tutorial we will explain the lifecycle of UIViewController in iOS, these methods will run in the following order:

1- init?(coder aDecoder: NSCoder)

If you are using storyboards this is where the controller is initialized, it is called one time only during the view controller lifetime.

2- loadView()

Creates the view that the controller manage, the view controller calls this method when its view property is requested but is currently nil.

This method loads or creates a view and assign it to the view property.

Never call this method directly.

3- viewDidLoad()

This called after the view is loaded into memory but bounds are not set yet.

This is a good place to initialize variables and setup one time only work because this method will run only one time, but do not do heavy work here because the view has not appeared on screen yet so the app may appear as freezing on the previous screen for some time.

4- viewWillAppear(_ animated: Bool)

This is called just before the view appear on screen so any time you go back and forward between views this method will be called.

This is a good place to show or hide controls or change status bar style

5-viewWillLayoutSubviews()

This may run several times.

Every time the bounds of the view change and the view is about to layout its subviews the system calls this method.

The default implementation of this method does nothing.

6- viewDidLayoutSubviews()

This may run several times.

Every time the bounds of the view change and the view finishes repositioning its subviews the system calls this method.

The default implementation of this method does nothing.

7- viewDidAppear(_ animated: Bool)

Notifies the view controller that the view appeared on screen.

It may run more than one time.

Here you can start animations, progress bars or getting external data from API

8- viewWillDisappear(_ animated: Bool)

Notifies the view controller that the view is about to disappear.

Might run more than one time.

Here you can resign first responder, dismiss keyboard, revert changes that you did in viewWillAppear like changing back status bar style or committing editing changes.

9- viewDidDisappear(_ animated: Bool)

Notifies the system that the view has been removed from the view hierarchy and disappeared.

May run more than one time.

Here you can stop services like audio or remove cached data.

Finally i would recommend reading UIViewController documentation from Apple since this is the most complete guide for iOS developers.

Hope you found it useful.

You might like What is the difference between Array, Set and Dictionary

Leave a Reply

Your email address will not be published. Required fields are marked *