views:

247

answers:

4

Let say here is my stack layout

View3     --> Top of the stack
View2
View1
HomeView  --> Bottom of the stack

So I am in View3 now, if I click the Home button, I want to load HomeView, meaning that I need to pop View3, View2, and View1. But if I pop View3, View2 will be displayed. I dont want that. I want View3, View2, and View1 be removed, and HomeView will be displayed. Any idea how?

+2  A: 

Use popToViewController

[self.navigationController popToViewController:homeView animated:YES];
Bird
How does it work? The documentation said you pop to a specific viewController, but I keep getting seg fault. U think u can give me a quick sample code?
Harry Pham
It's pop the view until the specific viewController is on the top of the stack. Can you post an error log and some of your code as well ?
Bird
Well, let say that I am in `aViewController` (assume that it already on the stack) , I push `bViewController`, then in `bViewController`, I `popToViewController:aViewController`, well but it said `aViewController` is undefined, which make sense since I am in `bViewController` now. I dont have reference to `aViewController`. Am I missing something?
Harry Pham
That's right, as @Ronnie Liew said. You need a reference.I usually pass this job to my delegate which have references to all of the related viewcontrollers. You can do this by [Protocol](http://stackoverflow.com/questions/626898/how-do-i-create-delegates-in-objective-c). (in your case, try `informal`)
Bird
+3  A: 

You can use popToRootViewControllerAnimated: to get to the root viewcontroller. This would pop out all the view controllers in the stack except the root view controller. In your case, this would be the HomeView.

[self popToRootViewControllerAnimated:YES];


To get to a specific view in the stack, you can use popToViewController:animated: Assuming you want to pop the third viewcontroller (from bottom up). In your case, this would be view2:

NSArray* viewControllersInStack = self.navigationController.viewControllers;
UIViewController* targetViewController = [viewControllersInStack objectAtIndex:2];
[self.navigationController popToViewController:targetViewController animated:YES];
Ronnie Liew
I have homeview as root in the example, but it is not the case in my code. TYVM :)
Harry Pham
I try that, but it said `HomeView` is undefined, which make sense since I am in `View3` so I dont have reference to `HomeView`, is that right?
Harry Pham
Yes you need a reference to the `HomeView`, and you can get that via the `self.navigationController.viewControllers` property
Ronnie Liew
I try to set the reference but it does not work. Access it via any array, well it messy, since u have to keep track of the index. Would you kindly enough to post some sample code on how to do PopToViewController, with access via reference, please?
Harry Pham
nvm, I got it working
Harry Pham
A: 

use...

[self.navigationController popToRootViewControllerAnimated:YES];