由init、loadView、viewDidLoad、viewDidUnload、dealloc的關係說起
init方法
- 在init方法中實例化必要的對象(遵從LazyLoad思想)
- init方法中初始化ViewController本身
loadView方法
- 當view需要被展示而它卻是nil時,viewController會調用該方法。不要直接調用該方法。
- 如果手工維護views,必須
重載重寫該方法 - 如果使用IB維護views,必須不能
重載重寫該方法 - loadView和IB構建view
viewDidLoad方法
重載重寫該方法以進一步定製view- 在iPhone OS 3.0及之後的版本中,還應該
重載重寫viewDidUnload來釋放對view的任何索引 - viewDidLoad後調用數據Model
viewDidUnload方法
- 當系統內存吃緊的時候會調用該方法(注:viewController沒有被dealloc)
- 內存吃緊時,在iPhone OS 3.0之前didReceiveMemoryWarning是釋放無用內存的唯一方式,但是OS 3.0及以後viewDidUnload方法是更好的方式
- 在該方法中將所有IBOutlet(無論是property還是實例變量)置爲nil(系統release view時已經將其release掉了)
- 在該方法中釋放其他與view有關的對象、其他在運行時創建(但非系統必須)的對象、在viewDidLoad中被創建的對象、緩存數據等
- release對象後,將對象置爲nil(IBOutlet只需要將其置爲nil,系統release view時已經將其release掉了)
- 一般認爲viewDidUnload是viewDidLoad的鏡像,因爲當view被重新請求時,viewDidLoad還會重新被執行
- viewDidUnload中被release的對象必須是很容易被重新創建的對象(比如在viewDidLoad或其他方法中創建的對象),不要release用戶數據或其他很難被重新創建的對象
dealloc方法
- viewDidUnload和dealloc方法沒有關聯,dealloc還是繼續做它該做的事情
舉例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/ * * The view hierarchy for this controller has been torn down . This usually happens in response to low memory notifications. * All IBOutlets should be released by setting their property to nil in order to free up as much memory as possible. * This is also a good place to release other variables that can be recreated when needed. * / - ( void ) viewDidUnload { self.startButton = nil; [setupViewController release]; setupViewController = nil; } - ( void ) dealloc { [startButton release]; [setupViewController release]; [super dealloc]; } |
看到以下的代碼
- (void)viewDidUnload {
self.detailViewController = nil;
self.languageNames = nil;
self.languageCodes = nil;
}
- (void)dealloc {
[detailViewController release];
[languageNames release];
[languageCodes release];
[super dealloc];
}