iphone NavigationController clear views stack

10,153

Solution 1

The following code will allow the user to drill down a view hierarchy, and at the press of a button, pop back to the root view controller and push a new view.

DetailViewController.m ~ the view controller from which to clear the navigation stack:

- (IBAction)buttonPressed:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"popBack" object:nil]];
}

The above code makes a call to NSNotificationCenter, posting a notification that the RootViewController can react to when heard. But first, the RootViewController must register to receive the notification.

RootViewController.m

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushViews) name:@"popBack" object:nil];
    [super viewDidLoad];
}

Next, the RootViewController must set up the referenced selector -pushViews.

- (void)pushViews {
     //Pop back to the root view controller
     [self.navigationController popToRootViewControllerAnimated:NO];

     //Allocate and init the new view controller to push to
     NewViewController *newVC = [[NewViewController alloc] init];

     //Push the new view controller
     [self.navigationController pushViewController:newVC animated:YES];
}

Be sure that when you call -popToRootViewControllerAnimated:, you specify NO for animation. Enabling animation causes hiccups in the navigation bar animation and confuses the system. The above code, when called, will clear the navigation stack, leaving only the RootViewController, and then adding the NewViewController.

The reason your initial code was not fully executing was because after calling -popToRootViewController: from your DetailViewController, the RootViewController's methods occupied the main thread, and the DetailViewController was released. Thus, no further code was run from that view controller. Using the code above, the navigation stack is popping back to the same view controller that is being loaded.

Solution 2

I think you're looking for -popToRootViewControllerAnimated:

Share:
10,153
Panos
Author by

Panos

Updated on June 05, 2022

Comments

  • Panos
    Panos almost 2 years

    I have an iphone application that uses a navigation controller. In that controller I push some views. In some cases I want to "clear" the views stack, leave only the rootViewController of the navigation controller in the stack and push another viewController I have.

    Can someone give me an example on how to do this? I don't see any method that clears the stack.


    Answer 1: I have tried to put in button Action the following code:

    [self.navigationController popToRootViewControllerAnimated:NO]; 
    
     do some stuff here to prepare for the push.
    
    [self.navigationController pushViewController:self.myOtherController animated:YES];
    

    but it only pops to the roorController. It doesn't push the other viewController I want.