Question

I am adding a child view controller to my primary view controller using the following code:

HPSPhotoLibraryOverlayController* controller = [[HPSPhotoLibraryOverlayController alloc] init];

[self.view addSubview:controller.view];

[self addChildViewController:controller];
[controller didMoveToParentViewController:self]; 

The view that the child view controller is controlling contains a button that when tapped should remove the child view and the child view controller from the primary view controller.

The method in the child view controller that runs when the button is pressed looks like this:

-(void)photoLibraryCloseButtonTapped:(id)sender
{
   [self.view removeFromSuperview];

   [(HPSFormController*)_parentController photoLibraryRequestingClose];
}

And then the method in the primary view controller that will close the child view controller looks like this:

-(void)photoLibraryRequestingClose
{
    UIViewController* controllerToRemove;
    for (UIViewController* controller in self.childViewControllers) {
        if ([controller isKindOfClass:[HPSPhotoLibraryOverlayController class]])
        {
            [controller removeFromParentViewController];
            controllerToRemove = controller;
        }

    }

    if (controllerToRemove)
    {
        controllerToRemove = nil;
    }

}

This code all works. However, it seems to me that the child view controller is being set to nil whilst the child view controller's -(void)photoLibraryCloseButtonTapped:(id)sender method is still running (i.e. the -(void)photoLibraryRequestingClose method has not yet returned, but I am nullifying the child view controller that has called photoLibraryRequestingClose.

I am using ARC.

Why does this work, and should I be managing the removal of the child view controller differently bearing in mind that the button to trigger the removal of the child controller is being managed by the child view controller.

Thanks very much.

Was it helpful?

Solution

Please have a look at Apples View Controller Programming Guide regarding Implementing a Custom Container View Controller especially at Listing 14-2:

- (void) hideContentController: (UIViewController*) content
{
   [content willMoveToParentViewController:nil];
   [content.view removeFromSuperview];
   [content removeFromParentViewController];
}

Answering your question you should change your code like this:

- (void)photoLibraryCloseButtonTapped:(id)sender
{
   [(HPSFormController*)_parentController photoLibraryControllerRequestingClose:self];
}

- (void)photoLibraryControllerRequestingClose:(UIViewController *)childController
{
   [childController willMoveToParentViewController:nil];
   [childController.view removeFromSuperview];
   [childController removeFromParentViewController];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top