18

Apple Documentation on UIViewController says:

If you are implementing your own container view controller, it must call the willMoveToParentViewController: method of the child view controller before calling the removeFromParentViewController method, passing in a parent value of nil.

When your custom container calls the addChildViewController: method, it automatically calls the willMoveToParentViewController: method of the view controller to be added as a child before adding it.

If you are implementing your own container view controller, it must call the didMoveToParentViewController: method of the child view controller after the transition to the new controller is complete or, if there is no transition, immediately after calling the addChildViewController: method.

The removeFromParentViewController method automatically calls the didMoveToParentViewController: method of the child view controller after it removes the child.

Why should I call these methods? What does those methods do?

ProfileViewController *profile = [[ProfileViewController alloc] init];
profile.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self addChildViewController:profile];
[self.view addSubview:profile.view];
[profile didMoveToParentViewController:self];

My code works perfectly even though I remove the last line. Can someone please help me in this?

Thanks in advance

Arun
  • 1,391
  • 1
  • 10
  • 29

2 Answers2

22

These methods are used because it is a rule to be followed when adding or removing a child view controller. Before adding a child view controller willMoveToParentViewController method should be called first followed by didMoveToParentViewController method. While removing child view controller from parent view controller these methods are to be called in reverse order.

addChildViewController: automatically calls [child willMoveToParentViewController:self]. So one should call didMoveToParentViewController after addChildViewController:. Similarly removeFromParentViewController: automatically calls [child didMoveToParentViewController:nil]. So one should call willMoveToParentViewController: before removeFromParentViewController:

Arun
  • 1,391
  • 1
  • 10
  • 29
2

Basically, they don't do anything that you can notice in the interface. "However, any subclass allows them to be overridden, so if you don't call them, you won't break a bare UIViewController, but you will break subclasses that rely on it (for instance: say a subclass wants to release an object when it is removed from a parent view controller, if you don't call the method, then it will never release the object)." as it was explained in the comments here.

Community
  • 1
  • 1
Darius Miliauskas
  • 3,391
  • 4
  • 35
  • 53