Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

didMoveToParentViewController called twice

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!

like image 513
notsoux Avatar asked Aug 19 '13 12:08

notsoux


1 Answers

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.

like image 185
user3204255 Avatar answered Sep 27 '22 03:09

user3204255