Are you familiar with viewWillAppear, viewDidAppear, viewDidLoad, viewWillDisappear and viewDidDisappear?

Before this, let me ask you what is the running order of viewWillAppear, viewDidAppear, viewDidLoad, viewWillDisappear and viewDidDisappear?

If you know the answer, please close this webpage and contine your game. :)

So a simple piece code is written to verify this:

Example code:

Objective-C Code
Swift Code for Swift lovers

Running results:

2017-04-14 08:18:18.923 TestBlock[3940:264012] viewDidLoad is running
2017-04-14 08:18:18.924 TestBlock[3940:264012] viewWillAppear is running
2017-04-14 08:18:18.946 TestBlock[3940:264012] viewDidAppear is running
2017-04-14 08:18:22.187 TestBlock[3940:264012] viewWillDisappear is running
2017-04-14 08:18:22.689 TestBlock[3940:264012] viewDidDisappear is running

After you click the button, you will see the order:

  1. viewDidLoad
  2. viewWillAppear
  3. viewDidAppear
  4. viewWillDisappear
  5. viewDidDisappear

More thoughts on this:

viewDidLoad: This method might be the most frequently used method while developing, normally we initialize data objects and controls. It will create all the necessary memory for all controls/data objects for this view. i.e. In the above case, anotherView and btnView, they will keep the same memory addresses for the whole life cycle.

viewWillAppear: Called before the view is added to the windows’ view hierarchy. So it is ideal for updating the viewcontroller’s data.

viewDidAppear: Called after the view is added to the windows’ view hierarchy.

viewWillDisappear: Called before the view is removed from the windows’ view hierarchy.

viewDidDisappear: Called after the view is removed from the windows’ view hierarchy.

Notice: There also used to be a method called viewDidUnload, it has been deprecated since the iOS 6, which used to do some final clean ups.


Show your support

Clapping shows how much you appreciated Ben Liu’s story.