ViewDidLoad method in UIViewController - when is it called?

I have a UIViewController called LaunchController that runs in my iPhone application the first time I open the application:

 @interface LaunchController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate> 

Then, when the button is pressed, I press another controller of the form:

  MainController *c = [[MainController alloc] initWithImage:image]; [self presentModalViewController:c animated:NO]; 

MainController has the following constructor that I use:

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

and then it has a viewDidLoad method as follows:

 - (void)viewDidLoad { NSLog(@"calling view did load"); [super viewDidLoad]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; [self.view addSubview:imageView]; NSLog(@"displaying main controller"); } 

When the program starts, I see that the constructor for MainController is MainController called (due to the output of NSLog ), however, viewDidLoad never being called, although I am calling presentModalViewController . Why is this? Why is viewDidLoad not called?

+7
source share
3 answers

I think this is something like follow-up. When you need the view property inside a UIViewController, it will be loaded in a lazy way.

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

After initializing the view it will call viewDidLoad to tell the UIViewController .

+4
source

You do not load your view controller from the xib file, and from the comments you have nothing in the loadView (where you should create a view controller view if you are not using the xib file).

Therefore, your view does not load, so viewDidLoad is never called.

Typically, you should use initWithNibName: to initialize a new view controller, and then set the image after it (to set the image as a property).

viewDidLoad will be called as soon as your controller view property is available, that is, when you first display it or request it (for example, get the code that calls c.view .

+3
source

The reason viewDidLoad is not called because you are not loading the view.

In your init method:

  self = [super init]; 

means you just create a bare view from scratch. without loading one of the threads.

try this instead:

 self = [super initWithNibName:nil bundle:nil]; 

If you have an xib or nib file with the same name as the view controller class, it should find if. Otherwise, you can just give the name nibName, which works.

UPDATE:

If you are not using nib files, then the corresponding method is NOT viewDidLoad. You should implement loadView instead of viewDidLoad .

In your specific case, just put everything that is currently in viewDidLoad into a loadView.

0
source

All Articles