Anubis
Anubis

Reputation: 1222

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?

Upvotes: 5

Views: 7121

Answers (2)

Gaurav Kaitwade
Gaurav Kaitwade

Reputation: 59

Swift 4

let viewcontrollers = self.navigationController?.viewControllers

viewcontrollers?.forEach({ (vc) in
        if  let inventoryListVC = vc as? InventoryListViewController {
            self.navigationController!.popToViewController(inventoryListVC, animated: true)
        }
    })

Upvotes: 2

MrDank
MrDank

Reputation: 2050

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)
}

Upvotes: 6

Related Questions