iOS的init、loadView, viewDidLoad, viewDidUnload, dealloc的關係

iOS的init、loadView, viewDidLoad, viewDidUnload, dealloc的關係   

轉自:http://www.cocoachina.com/bbs/read.php?tid=126158
由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還是繼續做它該做的事情
舉例:
12345678910111213141516/* * The view hierarchy for this controller has been torn down. This usually happens inresponse to low memory notifications. * All IBOutlets should be released by setting their property to nil in order to free upas 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];} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章