时间:2021-06-20 08:48:05 | 栏目:iOS代码 | 点击:次
IOS视图控制器
所谓的生命周期,也就是几个函数的调用顺序,这里以用Storyboard来创建一个ViewController为例
然后我们测试如下代码
// // ViewController.m // // Created by huangwenchen on 14/12/26. // Copyright (c) 2014年 huangwenchen. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (id)initWithCoder:(NSCoder *)aDecoder{ if (self = [super initWithCoder:aDecoder]) { NSLog(@"initWithCoder Called"); } return self; } - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"viewDidLoad Called"); // Do any additional setup after loading the view, typically from a nib. } - (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; NSLog(@"viewWillAppear Called"); } -(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; NSLog(@"viewDidAppear Called"); } -(void)awakeFromNib{ NSLog(@"awakeFromNib Called"); } -(void)viewWillLayoutSubviews{ NSLog(@"viewWillLayoutSubviews Called"); } -(void)viewDidLayoutSubviews{ NSLog(@"viewDidLayoutSubviews Called"); } @end
然后,在模拟器上运行,输出为
2014-12-29 19:42:47.904 KVCForCSDN[2370:126741] initWithCoder Called 2014-12-29 19:42:47.907 KVCForCSDN[2370:126741] awakeFromNib Called 2014-12-29 19:42:47.927 KVCForCSDN[2370:126741] viewDidLoad Called 2014-12-29 19:42:47.927 KVCForCSDN[2370:126741] viewWillAppear Called 2014-12-29 19:42:47.961 KVCForCSDN[2370:126741] viewWillLayoutSubviews Called 2014-12-29 19:42:47.963 KVCForCSDN[2370:126741] viewDidLayoutSubviews Called 2014-12-29 19:42:47.970 KVCForCSDN[2370:126741] viewDidAppear Called
所以,调用顺序为
1 init函数(init;initWithFrame;initWithCoder;等)--初始化
2 awakeFromNib--在loadView之前的工作放在这里
3 viewDidLoad--注意,一个ViewController一个生命周期内这个函数只会调用一次
4 viewWillAppear -- view将要出现,每次View消失再出现都会调用
5 viewWillLayoutSubviews--简要对子试图进行布局
6 viewDidLayoutSubivews--完成对子试图布局
7 viewDidAppear--视图将要出现在屏幕上
---上述代码不含部分
8 viewWillDisappear--View将要消失
9 viewDidDisappear--View已经消失
这九个就是通常的视图控制器生命周期内函数调用顺序,一定要清楚什么样的代码应该放在视图控制器生命周期的什么位置
BTY:
didReceiveMemoryWarning
这个函数通常也在生命周期的考虑范围内,当内存不足时候会调用,这时候应当进行适当的内存释放,不然iOS会强制关闭当前的APP
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!