iOS pushViewController 有坑

背景:在pushViewController之后把之前的vc删掉

先上代码

UIViewController *tempVC = [[UIViewController alloc] init];
[self.navigationController pushViewController:tempVC animated:YES];
NSMutableArray * subVCs = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
        for (int i=0; i<subVCs.count; i++) {
            if ([subVCs[i] isKindOfClass:[XXX class]]) {
                [subVCs removeObjectAtIndex:i];
            }
        }
        [self.navigationController setViewControllers:subVCs animated:YES];

大家一般都是这样做,可是,但是,pushViewController执行之后,有一定概率self.navigationController.viewControllers没有你刚才push的vc,这就是坑,它不是立马入栈的。


解决方法,很简单

  • 设置代理
    self.navigationController.delegate = self;
  • 实现代理函数
NSMutableArray * subVCs = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
        for (int i=0; i<subVCs.count; i++) {
            if ([subVCs[i] isKindOfClass:[XXX class]]) {
                [subVCs removeObjectAtIndex:i];
            }
        }
        [self.navigationController setViewControllers:subVCs animated:YES];

嗯,是不是很简单。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容