S.P. S.P. - 1 month ago 18
Objective-C Question

How to check a uiviewcontroller is present in uinavigationcontroller stack

I have a

UINavigationController
. I have to pop a view from a
UINavigationController
and replace it with another view. How we can search for a
UIViewController
object and replace it with another ?

when i print

NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray: myDelegate.navigationController.viewControllers];


I tried..

[allViewControllers removeObjectIdenticalTo: @"NonLogginedViewController"];
[allViewControllers removeObjectIdenticalTo: myDelegate.nonLogginedViewController];
myDelegate.navigationController.viewControllers = allViewControllers;


But it didn't update the
UINavigationController
stack ..
I don't know how to use
removeObjectIdenticalTo
with
UINavigationController
stack..

Please help me ..

Answer


Firstly, your test:

[allViewControllers removeObjectIdenticalTo: @"NonLogginedViewController"];

...is testing for a string, not a view controller. So that won't work.

If you know where the view controller is in the navigation controller's stack then this is easy. Say for example you've just pushed a new controller and now you want to remove the one before that. You could do this:

NSMutableArray *allControllers = [self.navigationController.viewControllers mutableCopy];
[allControllers removeObjectAtIndex:allControllers.count - 2];
[self.navigationController setViewControllers:allControllers animated:NO];

But I think in your case you want to find a certain controller and remove it. One way to do this would be to look for a certain class, e.g. LoginController. Set up a new array by copying the old one, and then iterate through this new array:

NSArray *allControllersCopy = [allControllers copy];

for (id object in allControllersCopy) {
   if ([object isKindOfClass:[LoginController class]])
      [allControllers removeObject:object];
}


...then set the allControllers array for the viewControllers property, as before.

NOTE: If you're manipulating a UINavigationController's stack from a containing view controller – perhaps once that view controller appears – you should wait until the view is fully onscreen. A good place for that is in the viewDidAppear: override, for example:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated]; 
    NSMutableArray *allControllers = ...
}
Comments