What is the difference between view controller life cycle and view life cycle in iOS?

MainstreamDeveloper00 picture MainstreamDeveloper00 · Feb 25, 2015 · Viewed 12.2k times · Source

Reading several tutorials and books on iOS development I often encounter terms : UIViewController life cycle and UIView life cycle. I'm interested: is there an actual difference between these two terms? Looking Apple docs I found that methods such as viewDidAppear or loadView is a part of view controller's life cycle, but I think it is more correct to refer them as view life cycle and methods such as initWithNibName or dealloc as controller's life cycle. Or there is no such a separation and when someone speaks about view life cycle he actually means UIViewController life cycle?

Answer

Tiago Almeida picture Tiago Almeida · Feb 25, 2015

Both are different concepts, therefore have different life cycles.

UIViewController

A ViewController is the Controller in a MVC architecture. Therefore, it is responsible to coordinate the info between the model (your data) and your views. UIViewControllers coordinate the UIViews and are part of navigation between screens (pushViewController, presentViewController). Therefore it needs to know when it will appear in the screen.

A UIViewController has a very specific life Cycle and it has methods that can be extended that are part of that life cycle. Examples of those methods are:

viewDidLoad, viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear

View

A View, on the other hand, shouldn't be worried when it has to appear on screen. Therefore, it has a complete different life cycle:

awakeFromNib, willMoveToSuperView, didMoveToSuperView

This methods usually are called in the sequence of the UIViewController's life cycle. Therefore, normally, the UIView responds to changes and people don't consider they have a Life cycle on their own.

The ViewController's life cycle only makes sense when a class extends UIViewController while a UIView's Life cycle only makes sense when extends UIView.

Most of the times, when people talk about Life cycle they will talk about the UIViewController life cycle, since the View usually responds to changes. Two examples of those changes are: the view changed its size, changes its parent.