Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

didMoveToParentViewController and willMoveToParentViewController

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

like image 692
Arun Avatar asked Aug 20 '15 09:08

Arun


1 Answers

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:

like image 51
Arun Avatar answered Sep 27 '22 22:09

Arun