How to segue back to a UIViewController that's already loaded?

TijuanaKez picture TijuanaKez · Apr 4, 2012 · Viewed 85.2k times · Source

I have a view on a storyboard the has a button to perform a certain action. To perform this action though, the user must be logged in. The button handler tests if the user is logged in and performs one segue if YES and another if NO. The NO segues pushes to a login view controller. There is another segue connecting back to the first view controller so if login is successfull the user can pick up where they left off. The view controllers are embedded in a navigation controller.

Problem is, the 'return' segue is loading a whole new instance of the view controller and not referencing the origional instance so I end up with empty interface elements and 2 copies of that view controller in memory.

How can I get back to the original instance of the view controller?

Answer

Mick MacCallum picture Mick MacCallum · Apr 4, 2012

Assuming by your use of "push" you mean that you are using a UINavigationController, then you can use the following to return to the top of the stack.

[self.navigationController popToRootViewControllerAnimated:YES];

or

UIViewController *prevVC = [self.navigationController.viewControllers objectAtIndex:<n>];
[self.navigationController popToViewController:prevVC animated:YES];

to pop to a specific level where <n> is the level.

or

[self.navigationController popViewControllerAnimated:YES];

If you just want to pop one level back up the navigation stack.