viewDidUnLoad的用法

 由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 memoryas 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];

}

 
如果是先調用viewDidUnload後再調用dealloc, 那麼languageNames都已經是nil了,再掉release有什麼意義呢?
 
原因似乎是, 對一個viewcontroller來說,它的數據的初始化在init中,而它管理的view採用了lazy load的方式,也就是有需要的時候纔會載入, 所以跟view相關的數據可以在viewDidLoad(也就是在view被載入的時候)進行初始化。
當內存緊張的時候, ios會銷燬點一些view, 通過調用viewDidUnload (裏面一般也只是把跟view相關的數據設爲nil), 但這個時候viewcontroller本身還在, 所以它的dealloc不會被調用,除非是到了viewcontroller也被銷燬的時候
 
轉自:http://zhgw01.blog.163.com/blog/static/104148122011844621458/
http://zyc-to.blog.163.com/blog/static/17152400201011299129231/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章