Sergey Grishchev
Sergey Grishchev

Reputation: 12051

Checking whether NavigationStack contains View Controller error

I'm trying to see if the View Controller is on Navigation stack and I'm lost in options of what to do. Here's what I'm trying to do:

if ([((AppDelegate *)[UIApplication sharedApplication].delegate).frontViewController.navigationController.viewControllers containsObject:SGAddNewServerViewController]) {
    <#statements#>
}

The problem is, how do I get the reference to SGAddNewServerViewController since I need to know its address with objectAtIndex... etc? XCode gives me an error of not knowing what it is and he's right.

Any ideas of how can I get a reference to it without knowing its exact address on the NavigationStack? Thanks.

Upvotes: 0

Views: 549

Answers (2)

rmaddy
rmaddy

Reputation: 318804

It appears you are trying to find the view controller based on its class. To do that, try this:

AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
UINavigationController *nav = delegate.frontViewController.navigationController;
for (UIViewController *controller in nav.viewControllers) {
    if ([controller isKindOfClass:[SGAddNewServerViewController class]]) {
        SGAddNewServerViewController *sgController = (SGAddNewServerViewController *)controller;
        // do stuff
    }
}

Please note that it is not a good idea to nest so many method/property calls into one line. It makes reading and debugging very difficult.

Upvotes: 1

Mikhail
Mikhail

Reputation: 4311

You can iterate over all controllers and check whether there is controller of type SGAddNewServerViewController

NSArray *viewControllers = ((AppDelegate *)[UIApplication sharedApplication].delegate).frontViewController.navigationController.viewControllers;
for (UIViewController *controller in viewControllers) {
    if ([controller isKindOfClass:[SGAddNewServerViewController class]]) {
        //todo something
    }
}

Upvotes: 1

Related Questions