I made a simple test to learn more about contained view controller.
I have a view controller where I added/removed a view controller using two buttons' action:
- (IBAction)myInfoAddAction:(id)sender {
profileViewController = [[ProfileViewController alloc] init];
[self addChildViewController: profileViewController];
UIView *__view = profileViewController.view;
[self.view addSubview: __view];
[profileViewController didMoveToParentViewController: self];
}
- (IBAction)myInfoRemoveAction:(id)sender {
[profileViewController willMoveToParentViewController: nil];
[profileViewController.view removeFromSuperview];
[profileViewController removeFromParentViewController];
}
Class ProfileViewController
extends UIViewController
and override willMoveToParentViewController
and didMoveToParentViewController
methods
-( void)willMoveToParentViewController:(UIViewController *)parent
{
[super willMoveToParentViewController: parent];
NSLog(@"willMoveToParentViewController -> %@", self);
}
-( void) didMoveToParentViewController:(UIViewController *)parent
{
[super didMoveToParentViewController: parent];
NSLog(@"didMoveToParentViewController -> %@", self);
}
-( void)viewWillAppear:(BOOL)animated
{
NSLog(@"viewWillAppear -> %@", self);
}
-( void)viewDidDisappear:(BOOL)animated
{
NSLog(@"viewDidDisappear -> %@", self);
}
When I add view controller, I got the following logs:
willMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
viewWillAppear -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
When I remove view controller:
willMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
viewDidDisappear -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
I'd like to know Why didMoveToParentViewController
is invoked twice?
Thanks!
I've had the same issue as well. Furthermore, I found that when I added the child view controller during viewDidLoad, I only had one message. I fixed it by removing the call to [super didMoveToParentViewController:]
. I think the issue has to do with adding child view controllers while in the callback from a button, but I'm not sure why this should cause an issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With