Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tried to pop to a view controller that doesn't exist

I'm trying to return to a previous view controller but I'm running to issues that (to my understanding) shouldn't be happening.

A short description of what I'm trying to do: I have 4 view controllers: A, B, C and D. The basic UI flow is A -> B -> C -> D. After finishing work in C, I want to return back to B.

My code:

let viewControllerArray = self.navigationController?.viewControllers
                for(var i=0;i<viewControllerArray?.count;i++){
                    if(viewControllerArray![i].isKindOfClass(InventoryListViewController)){
                        self.navigationController?.popToViewController(viewControllerArray![i], animated: true)
                    }
                }

This all works fine if B still exists on the navigationcontroller's stack. If B has been removed from the stack (due to memory-related reasons) it gives me a Tried to pop to a view controller that doesn't exist error (obviously). The thing I'm confused about is that shouldn't the If-statement prevent the popToViewController method from getting called if B doesn't exist on the stack anymore?

like image 667
Anubis Avatar asked Mar 17 '16 10:03

Anubis


People also ask

How do I open a new view controller?

To create a new view controller, select File->New->File and select a Cocoa Touch Class. Choose whether to create it with Swift or Objective-C and inherit from UIViewController . Don't create it with a xib (a separate Interface Builder file), as you will most likely add it to an existing storyboard.


1 Answers

The best way to prevent a crash is by optional unwrapping. Try this code and let me know if it solves the issue.

let allVC = self.navigationController?.viewControllers

if  let inventoryListVC = allVC![allVC!.count - 2] as? InventoryListViewController {   
self.navigationController!.popToViewController(inventoryListVC, animated: true)
}
like image 68
MrDank Avatar answered Oct 11 '22 10:10

MrDank