检查导航堆栈上是否存在ViewController

时间:2013-01-17 12:11:56

标签: iphone ios objective-c cocoa-touch uinavigationcontroller

我这里有这段代码来检查ViewController的存在。不幸的是它不起作用。问题是,它是从Navigation Stack弹出的另一个VC 目前执行

- (void) leftViewDidHide{
    if ([((AppDelegate *)[UIApplication sharedApplication].delegate).frontViewController.navigationController.viewControllers objectAtIndex:1]) {
    SGServerListViewController *sample = [[[((AppDelegate *)[UIApplication sharedApplication].delegate).frontViewController.navigationController.viewControllers objectAtIndex:1]childViewControllers] objectAtIndex:0];
    [sample.serverTableView setUserInteractionEnabled:YES];
    }
}

应用程序崩溃,异常断点将我指向带有if语句的行。关于这里可能出现什么问题的任何想法?我只是想检查这个VC是否存在,如果是 - 执行代码。

6 个答案:

答案 0 :(得分:7)

NSArray *viewControlles = [self.navigationController.viewControllers];

for (int i = 0 ; i <viewControlles.count; i++){ 
  if ([YourVC isKindOfClass:[viewControlles objectAtIndex:i]]) {
          //Execute your code
      }
}

答案 1 :(得分:5)

 NSArray *controllerArray = [self.navigationController.viewControllers];
//will get all the controllers added to UINavigationController.

    for (id controller in controllerArray)
   { 
      // iterate through the array and check for your controller
      if ([controller isKindOfClass:[checkYourController class]]) 
          {
              //do your stuff here
          }
    }

只是为了containsObject:类的NSArray方法也可能有效。

答案 2 :(得分:2)

-(BOOL)isControllerAlreadyOnNavigationControllerStack{

    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:Controller.class]) {
            [self.navigationController popToViewController:vc animated:NO];
            return YES;
        }
    }
    return NO;
}


if (![self isControllerAlreadyOnNavigationControllerStack]) {
    //push controller 
}

答案 3 :(得分:1)

- (void) leftViewDidHide{

if ([((AppDelegate *)[UIApplication sharedApplication].delegate).frontViewController.navigationController.viewControllers count] == 1) {

         SGServerListViewController *sample = [[[((AppDelegate *)[UIApplication sharedApplication].delegate).frontViewController.navigationController.viewControllers objectAtIndex:1]childViewControllers] objectAtIndex:0];
         [sample.serverTableView setUserInteractionEnabled:YES];

     }
 }

答案 4 :(得分:1)

您可以使用以下代码执行此操作(检查导航堆栈上是否存在ViewController):

if navigationController?.viewControllers.count > 1 {
    for root in (self.navigationController?.viewControllers)! {
        if root is ViewController {
           let i = root as? ViewController
            i?.table.removeFromSuperview()
        }
    }
}
self.navigationController?.popToRootViewControllerAnimated(true)

答案 5 :(得分:0)

NSArray *viewControlles = self.navigationController.viewControllers;

for (int i = 0 ; i <viewControlles.count; i++){
    if ([[viewControlles objectAtIndex:i] isKindOfClass:[RequiredViewController class]]) {

        //Enter your code

    }
}