从ARK中的导航堆栈以编程方式删除视图控制器

时间:2012-12-04 11:16:53

标签: objective-c ios cocoa-touch uinavigationcontroller automatic-ref-counting

在推送第3个新的ViewController之前,我想清除具有两个视图控制器的导航堆栈。我正在做以下事情:

NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];

for (int i = 0; i < [viewControllerArray count]; i++) {
      [viewControllerArray removeObjectAtIndex:i]; 
      //here the [viewControllerArray count] is 2,but loop is iterated only once.
}

self.navigationController.viewControllers=viewControllerArray;

NSLog(@"View Controller Array %@",[self.navigationController viewControllers])
//This will print null which I assume is correct.

然后我推送新的ViewController,如下所示:

  DetailViewController *detailView=[[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];

  [self.navigationController pushViewController:detailView animated:YES];

但是我的新视图没有被推送,而是显示导航堆栈中存在的最顶层视图。我觉得这很奇怪,因为我已经删除了ViewControllers并将其打印在NSLog中,显示为null。

2 个答案:

答案 0 :(得分:3)

DetailViewController *detailView = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];    
NSMutableArray *viewControllerArray = [self.navigationController.viewControllers mutableCopy];
[viewControllerArray removeAllObjects];
[viewControllerArray addObject:detailView];
[self.navigationController setViewControllers:viewControllerArray animated:YES];

试试这个。

答案 1 :(得分:1)

在按下第三个视图并从第三个视图控制器中删除第二个视图控制器之前,尝试删除一个视图控制器。使用循环删除多个viewController有时可能会导致错误。