DevC
DevC

Reputation: 7022

Modal View Controller, dismiss and pop back to view controller

Im trying to dismiss a ModaViewController called C, back to A. The ModalViewController is presented in B. Therefore the Navigation flow is A->B - (present ModalView) -> C. I am able to dismiss the ModalViewController back to B, but I am unable to pop back to A in the completion bracket. This is the code I have tried:

[self dismissViewControllerAnimated:YES completion:^{
    [self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:0] animated:YES];
}];

The ModalViewController is dismissed but does not pop back to A. I call this block of code in an IBAction.

Any advice?

On a second note, when I dismiss the ModalViewController all my UIPickers in Controller B are empty/ deallocated. I am using ARC as well.

Upvotes: 6

Views: 7378

Answers (2)

rdelmar
rdelmar

Reputation: 104092

The problem with your code is that self.navigationController will be nil. If you have a controller (A) embedded in a navigation controller, and that controller pushes to another controller (B) which then presents your last controller (C), then you need to do something like this,

-(IBAction)dismissToBThenPop:(id)sender {
    UINavigationController *nav = (UINavigationController *)self.presentingViewController;
    [self dismissViewControllerAnimated:YES completion:^{
        [nav popViewControllerAnimated:YES];
    }];
}

Even though you present C from B, the actual presentingViewController will be the navigation controller. This code will dismiss C then pop B, but you will see B for an instant before ut pops back to A. If you don't want to see this, then you should use an unwind segue to go directly back to A from C.

Your second problem about the pickers being empty and deallocated should not be happening under the scenario that you say you have. You will have to provide more information about what you're doing in B to solve that problem.

Upvotes: 12

Durican Radu
Durican Radu

Reputation: 1337

Create a protocol in ModalViewController, let's say ModalViewControllerDelegate with a method -(void)dismissTheModal, and make B implement this protocol. Before showing the ModalViewController, do modalViewController.delegate = self. When you're IBAction is called, do [self.delegate dismissTheModal], and in controller B you should do :

 -(void)dismissTheModal {
     [self dismissViewControllerAnimated:YES completion:^{
         [self popViewController];
  }];  

Upvotes: 0

Related Questions