IOS视图生命周期

时间:2022-09-02 14:43:07

以视图的4种状态为基础,我们来系统了解一下视图控制器的生命周期。在视图不同的生命周期中,视图控制器会回调不同的方法,具体如图所示

IOS视图生命周期

1.viewDidLoad方法开发文档中的解释:

- (void)viewDidLoad; 
// Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.
在视图控制器已被实例化,视图被加载到内存中时,会调用viewDidLoad方法,这时视图并未出现。在该方法中,通常会对所控制的视图进行初始化处理。如设置导航栏的标题和返回按钮:

self.title = @"标题";
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(function)];
2.viewWillAppear,viewDidAppear,viewWillDisappear,viewDidDisappear方法 开发文档中的解释:

- (void)viewWillAppear:(BOOL)animated;    
// Called when the view is about to made visible. Default does nothing
- (void)viewDidAppear:(BOOL)animated;
// Called when the view has been fully transitioned onto the screen. Default does nothing
- (void)viewWillDisappear:(BOOL)animated;
// Called when the view is dismissed, covered or otherwise hidden. Default does nothing
- (void)viewDidDisappear:(BOOL)animated;
// Called after the view was dismissed, covered or otherwise hidden. Default does nothing
视图可见前后会调用viewWillAppear:方法和viewDidAppear:方法,视图不可见前后会调用viewWillDisappear:方法和viewDidDisappear:方法。这4个方法调用父类相应的方法以实现其功能,编码时调用父类方法的位置可根据实际情况做调整,参见如下代码:

- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
viewDidLoad方法在应用运行的时候只调用一次,而上述这4个方法可以被反复调用多次,一些需要每次打开页面都执行的方法可以写在viewWillAppear方法中,如刷新界面,查询数据等。

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.tableView reloadData];
}
3.didReceiveMemoryWarning方法 开发文档中的解释:

- (void)didReceiveMemoryWarning; 
// Called when the parent application receives a memory warning. On iOS 6.0 it will no longer clear the view by default.
在低内存的情况下,IOS会调用didReceiveMemoryWarning和viewDidUnload方法。在IOS6之后就不再调用viewDidUnload方法,而仅支持didReceiveMemoryWarning方法。didReceiveMemoryWarning方法的主要职能是释放内存,包括视图控制器中的一些成员变量和视图的释放。

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}