所謂的生命周期,也就是幾個函數的調用順序,這裡以用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