ViewController生命周期
alloc -> initWithNibName -> loadView -> viewDidLoad -> viewWillAppear -> viewDidAppear -> viewWillDisappear -> viewDidDisappear -> dealloc
注意viewWillUnload和viewDidUnload已经在ios6被废弃了,因为Clearing references to views is no longer necessary。
注意1.没有viewWillLoad。
注意2.viewDidLoad和viewDidUnload并不是成对的。
某些情况下的方法调用流程:
- pushViewController 和 presentViewController 方法实现的 A视图控制器 到 B视图控制器的过渡,会按顺序触发 (A)viewWillDisappear->(B)viewWillAppear->(A)viewDidDisappear->(B)viewDidAppear
- 右滑返回手势、 popViewController 和 dismissViewControllerAnimated 方法实现的 B视图控制器 到 A视图控制器的过渡则会按顺序触发 (B)viewWillDisappear->(A)viewWillAppear->(B)viewDidDisappear->(A)viewDidAppear
右滑退出事件统计:
右滑触发viewWillDisappear后有可能是退出,也有可能不退出;而点击返回退出和右滑退出都会触发viewDidDisappear,这里需要用到转场协调器(
UIViewControllerTransitionCoordinator)
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
{
id<UIViewControllerTransitionCoordinator> tc = self.navigationController.topViewController.transitionCoordinator;
[tc notifyWhenInteractionEndsUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// 交互式过渡操作结束调用的代码块,右滑结束(不管是否pop成功),如果不成功会在这个代码块结束后调用viewWillAppear
_interactivePopExit = YES; // 全局变量,YES表示右滑成功退出,NO表示失败
}];
}
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
_interactivePopExit = NO; // 右滑退出操作未能pop
}
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
if (_interactivePopExit) {
NSLog(@"边缘右滑退出");
}
}