UIViewController中的ViewDidLoad方法 - 什么时候被调用?

Cod*_*Guy 7 iphone uiviewcontroller ios

我有一个UIViewController名为LaunchController的应用程序首次打开时在我的iPhone应用程序中启动:

@interface LaunchController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
Run Code Online (Sandbox Code Playgroud)

然后,当单击一个按钮时,我推送另一个视图控制器:

 MainController *c = [[MainController alloc] initWithImage:image];
 [self presentModalViewController:c animated:NO];
Run Code Online (Sandbox Code Playgroud)

MainController有以下构造函数,我使用它:

- (id)initWithImage:(UIImage *)img
{
    self = [super init];
    if (self) {
        image = img;
        NSLog(@"inited the image");
    }

    return self;
}
Run Code Online (Sandbox Code Playgroud)

然后它有一个viewDidLoad方法如下:

- (void)viewDidLoad
{
    NSLog(@"calling view did load");
    [super viewDidLoad];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.view addSubview:imageView];
    NSLog(@"displaying main controller");
}
Run Code Online (Sandbox Code Playgroud)

当程序运行时,我看到构造函数MainController被调用(由于输出NSLog),但是viewDidLoad永远不会被调用,即使我正在调用presentModalViewController.为什么是这样?为什么不viewDidLoad被召唤?

Aec*_*Liu 4

我认为是以下内容。当你需要UIViewController内部的属性时view,它会以惰性方式加载。

- (UIView *)view 
{
   if (_view == nil) {
      [self loadView]; //< or, the view is loaded from xib, or something else.
      [self viewDidLoad];
   }

   return _view;
} 
Run Code Online (Sandbox Code Playgroud)

初始化完成后view,会调用viewDidLoad通知UIViewController

  • @amatn:你是对的。但我只是使用上面的代码来描述`-viewDidLoad`何时被调用。 (4认同)