loadView VS viewDidLoad

iPhone開發必不可少的要用到這兩個方法。 他們都可以用來在視圖載入的時候,初始化一些內容。 但是他們有什麼區別呢?

viewDidLoad 此方法只有當view從nib文件初始化的時候才被調用。

loadView 此方法在控制器的view爲nil的時候被調用。 此方法用於以編程的方式創建view的時候用到。 如:

  1.  
  2. ( void ) loadView {
  3.     UIView *view = [ [ UIView alloc] initWithFrame:[ UIScreen
  4. mainScreen] .applicationFrame] ;
  5.     [ view setBackgroundColor:_color] ;
  6.     self.view = view;
  7.     [ view release] ;
  8. }
  9.  

你在控制器中實現了loadView方法,那麼你可能會在應用運行的某個時候被內存管理控制調用。 如果設備內存不足的時候, view 控制器會收到didReceiveMemoryWarning的消息。 默認的實現是檢查當前控制器的view是否在使用。 如果它的view不在當前正在使用的view hierarchy裏面,且你的控制器實現了loadView方法,那麼這個view將被release, loadView方法將被再次調用來創建一個新的view。

 

--------------------------------------------------------------------------------------------------------------------------------------------

Don't read self.view in -loadView. Only set it, don't get it.

The self.view property accessor calls -loadView if the view isn't currently loaded. There's your infinite recursion.

The usual way to build the view programmatically in -loadView, as demonstrated in Apple's pre-Interface-Builder examples, is more like this:

UIView * view = [[ UIView alloc ] init ...]; 
... 
[ view addSubview : whatever ]; 
[ view addSubview : whatever2 ]; 
... 
self . view = view ; 
[ view release ]; 

And I don't blame you for not using IB. I've stuck with this method for all of Instapaper and find myself much more comfortable with it than dealing with IB's complexities, interface quirks, and unexpected behind-the-scenes behavior.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章