现在的位置: 首页 > 综合 > 正文

loadView VS viewDidLoad

2014年02月25日 ⁄ 综合 ⁄ 共 1357字 ⁄ 字号 评论关闭

iPhone开发必不可少的要用到这两个方法。 他们都可以用来在视图载入的时候,初始化一些内容。 但是他们有什么区别呢?

viewDidLoad 此方法只有当view从nib文件初始化的时候才被调用。

loadView 此方法在控制器的view为nil的时候被调用。 此方法用于以编程的方式创建view的时候用到。 如:

 
- ( void ) loadView { 
    UIView *view = [ [ UIView alloc] initWithFrame:[ UIScreen mainScreen] .applicationFrame] ;
    [ view setBackgroundColor:_color] ;
    self.view = view;
    [ view release] ;

你在控制器中实现了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.

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/WTK870424/archive/2010/01/25/5252922.aspx

抱歉!评论已关闭.