initWithCoder:(NSCoder *)aDecoder:
加载xib,storyboard,纯代码用不到
loadView:
加载view
viewDidLoad:
view加载完毕
viewWillAppear:
控制器的view将要显示
viewWillLayoutSubviews:
控制器的view将要布局子控件
viewDidLayoutSubviews:
控制器的view布局子控件完成
这期间系统可能会多次调用viewWillLayoutSubviews
、 viewDidLayoutSubviews
俩个方法
viewDidAppear:
控制器的view完全显示
viewWillDisappear:
控制器的view即将消失的时候
这期间系统也会调用viewWillLayoutSubviews
、viewDidLayoutSubviews
两个方法
viewDidDisappear:
控制器的view完全消失的时候
didReceiveMemoryWarning
当app收到内存警告的时候会发消息给视图控制器。
viewWillUnload:
(iOS6废除)
viewDidUnload:
(iOS6废除)
总结:
整个控制器声明周期:
viewDidLoad -> viewWillAppear -> viewWillLayoutSubviews -> viewDidLayoutSubviews -> viewDidAppear -> viewWillDisappear -> viewDidDisappear
Demo
控制器1:(跳转到控制器2代码类似)
@interface ViewController ()
@property (nonatomic, assign)NSInteger count;
@end
@implementation ViewController
- (instancetype)init {
self = [super init];
if (self) {
self.count = 0;
}
return self;
}
- (void)loadView {
[super loadView];
NSLog(@"ViewController%s------%ld", __func__, (long)self.count);
self.count++;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"ViewController%s------%ld", __func__, (long)self.count);
self.count ++;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.count++;
NSLog(@"ViewController%s------%ld", __func__, (long)self.count);
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.count++;
NSLog(@"ViewController%s------%ld", __func__, (long)self.count);
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
self.count++;
NSLog(@"ViewController%s------%ld", __func__, (long)self.count);
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
self.count++;
NSLog(@"ViewController%s------%ld", __func__, (long)self.count);
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
self.count++;
NSLog(@"ViewController%s------%ld", __func__, (long)self.count);
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.count++;
NSLog(@"ViewController%s------%ld", __func__, (long)self.count);
}
- (IBAction)buttonClick:(id)sender {
Test1ViewController *test = [[Test1ViewController alloc] init];
[self.navigationController pushViewController:test animated:YES];
}
打印结果:
-
push的时候生命周期:
-
pop的时候生命周期:
参考文章:
https://www.jianshu.com/p/42eb5a930d66
http://www.cocoachina.com/cms/wap.php?action=article&id=23326
iOS系统中导航栏的转场解决方案与最佳实践