Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if controller is already on navigationcontroller viewcontrollers stack?

i'm getting this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Pushing the same view controller instance more than once is not supported

How does one check if a controller already exists in the stack and not push that controller but move to it?

Here's some code where I'm pushing a controller based on a tab selection:

func tabSelected(tab: String) {
    switch tab{
    case "payment":
        mainNavigationController.popToViewController(myAccountViewController, animated: true)
    break
    case "delivery":
        mainNavigationController.pushViewController(deliveryViewController, animated: true)
        break
    case "service":
        mainNavigationController.pushViewController(serviceViewController, animated: true)
        break
    case "profile":
        mainNavigationController.pushViewController(profileViewController, animated: true)
        break
    default:
        break
    }
}
like image 677
Sam Luther Avatar asked Sep 16 '25 02:09

Sam Luther


1 Answers

It seems like you are pushing a same controller to your navigation stack. You can't push a view controller onto the stack that already exists in the stack. It is probably that you call you tabSelected() method multiple times, so you should make sure it doesnt get called multiple times.

A good practice to prevent your crash is to pop off the existing controller, which already in the stack. So you should do something like self.navigationController?.popToViewController(myViewController, animated: true) whenever you leave your view controller.

Or you can do the following to check whatever your controller is already in the stack:

 if (self.navigationController?.topViewController.isKindOfClass(ViewController) != nil) {

}

For your particular case, do the following:

if(mainNavigationController.topViewController.isKindOfClass(ProfileViewController) != nil) {

    }
like image 171
ztan Avatar answered Sep 17 '25 17:09

ztan