這三個方法都屬於 UIViewController,緊緊綁著 view 屬性的生命週期。搞懂它們各自的職責與觸發時機,才能避免把初始化寫錯地方、把資源釋放錯時機。
什麼時候被呼叫?每次存取 controller.view、self.view 這類 view 屬性,而此時 view 為 nil,loadView 就會被觸發。
它的職責是什麼?專門負責把 view 建出來。
預設實做了哪些事?也就是 [super loadView] 的內容,大致分兩步:
[[MJViewController alloc] initWithNibName:@"MJViewController" bundle:nil]; [[MJViewController alloc] init]; // 載入 MJViewController.xib
self.view = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
正確用法。xib 很方便,但有些場合它就是不夠靈活,這時我們會想用純程式碼建 view:
self.view = [[[UIWebView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
要這麼做就必須覆寫 loadView,而且不要呼叫 [super loadView]。原因上面說過:找不到 xib 時,父類實作會先建一個空白 UIView,而你既然要自己客製,那個空白 view 就是純粹的浪費。標準寫法:
- (void)loadView {
self.view = [[[UIWebView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
}
多呼叫一次 [super loadView] 不會出錯,只是白做工。一句話總結:蘋果留這個方法給你,就是為了自訂 view。
什麼時候被呼叫?不論 view 是來自 xib 還是覆寫的 loadView,只要 view 建好,最後都會走到 viewDidLoad。
它的職責是什麼?做介面上的初始化:加子視圖、把資料庫或網路取得的模型裝到控制項上。
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
[button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
什麼時候被呼叫?iOS 的記憶體有限,當 App 吃太多記憶體時系統會發出警告,controller 收到 didReceiveMemoryWarning。其預設實作會檢查:如果自己的 view 目前不在視圖階層中(superview 為 nil),就把 view 釋放並呼叫 viewDidUnload。
它的職責是什麼?清界面相關的資源,把對應實例設為 nil。
- (void)viewDidUnload {
[super viewDidUnload];
self.name = nil;
self.pwd = nil;
}
那它和 dealloc 差在哪?發出記憶警告而呼叫 viewDidUnload 時,被放掉的只有 view,controller 本身還活著,所以 dealloc 不會被觸發。兩者沒有任何關聯——dealloc 只在 controller 自己被釋放時才會呼叫。
最後一點特別值得記住:viewDidLoad 裡的邏輯有可能被執行第二次,所以不要把只能做一次的副作用(例如計時器啟動、上報請求)寫在裡面而沒有防護。