Ios – Container UIViewController Not Releasing it’s Child View Controllers

automatic-ref-countingiosuiviewcontroller

I have a custom container UIViewController that has six child UIViewControllers, and a set of tabs that the user interacts with to switch between the child view controllers. The problem is when my container view controller is released the child view controllers are not.

I have verified that the child view controllers are not released by adding some debugging code to their dealloc methods, and they are released as long as their view's are not added to the container view controller's view.

Below is an a excerpt of the code I'm using to create my custom container view controller. The viewController pointers are iVars. I am also using ARC so that is why there are no actual release calls.

- (void)init 
{
    if ((self = [super init])) { 
        vc1 = [[UIViewController alloc] init];
        [self addChildViewController:vc1];

        vc2 = [[UIViewController alloc] init];
        [self addChildViewController:vc2];

        vc3 = [[UIViewController alloc] init];
        [self addChildViewController:vc3];

        vc4 = [[UIViewController alloc] init];
        [self addChildViewController:vc4];

        vc5 = [[UIViewController alloc] init];
        [self addChildViewController:vc5];

        vc6 = [[UIViewController alloc] init];
        [self addChildViewController:vc6];
    }
    return self;
}

- (void)dealloc
{
    [vc1 removeFromParentViewController];
    vc1 = nil;

    [vc2 removeFromParentViewController];
    vc2 = nil;

    [vc3 removeFromParentViewController];
    vc3 = nil;

    [vc4 removeFromParentViewController];
    vc4 = nil;

    [vc5 removeFromParentViewController];
    vc5 = nil;

    [vc6 removeFromParentViewController];
    vc6 = nil;
}

- (void)switchFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController
{
    if (fromViewController) {
        [fromViewController.view removeFromSuperview];
    }

    [self.view addSubview:toViewController];
    toViewController.view.frame = self.view.bounds;
}

Do you all have any ideas what I'm doing wrong?

Best Answer

This is not the way to add and remove child view controllers

    [childViewController willMoveToParentViewController:nil];
    [childViewController view] removeFromSuperview];
    [childViewController removeFromParentViewController];

is the way to remove and to add it is

    [parentViewController addChildViewController:childViewController];
    [parentViewController.view addSubview:childViewController.view];
    [childViewController didMoveToParentViewController:parentViewController];
Related Topic