How to correctly dismiss child view controller

Embedded view controllers are always a good thing to have, but when loading and dismissing them, what is the correct order?

Compare to dismiss a normal view controller by calling:

[viewController dismissViewControllerAnimated:NO completion:^{..}];

Embedded child view controller have a lot to do. I’ve read the apple documents carefully to summarize the following steps for loading and dismissing a child view controller.

First the loading steps :

  1. Call the addChildViewController: method of your container view controller.
    This method tells UIKit that your container view controller is now managing the view of the child view controller.
  2. Add the child’s root view to your container’s view hierarchy.
    Always remember to set the size and position of the child’s frame as part of this process.
  3. Add any constraints for managing the size and position of the child’s root view.
  4. Call the didMoveToParentViewController: method of the child view controller.

And the right way to dismiss it:

  1. Call the child’s willMoveToParentViewController: method with the valuenil.
  2. Remove any constraints that you configured with the child’s root view.
  3. Remove the child’s root view from your container’s view hierarchy.
  4. Call the child’s removeFromParentViewController method to finalize the end of the parent-child relationship.

Hope it’s helpful.