Ios – loadView of UIViewController not called

iosiphoneuiviewuiviewcontroller

I want to setup a UIViewController within a NavigationController programmatically, however the loadView nor viewDidLoad method get called.

This is my code in the app delegate:

MyViewController *viewController = [[MyViewController alloc] init];
UIView *view = [[UIView alloc] initWithFrame:window.frame];
viewController.view = view;

UINavgationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];

[window addSubview:[navController view];
[window makeKeyAndVisible];

When I start the app I see a navigationbar, but no calls to loadView. What am I missing?
I thought loadView gets called after you call view

Edit

MyViewController *viewController = [[MyViewController alloc] init];
[viewController view];  // doesn't look right?

UINavgationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];

[window addSubview:[navController view];
[window makeKeyAndVisible];

edited towards Jonah's comment, but loadView still doesn't get called.

Best Answer

A UIViewController will create its view (by loading it from a nib or implementing -loadView) when the controller's view getter is called and its view is currently nil.

In the code shown you never invoke the view property's getter, only its setter.

Also, you are assigning the controller's view from your app delegate. UIViewControllers are expected to create their own views on demand, not have them provided by some other class. This approach will cause you problems later when you realize that the controller unloads its view and attempts to recreate it in response to memory warnings. Let your controller create its view, don't try to pass it one.

Related Topic