7

I'm trying to access navigationController from UIViewController, for some reason it equals nil

AppDelegate:

self.mainViewController = [[MainViewController alloc] init];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.mainViewController];
self.window.rootViewController = self.navigationController;

MainViewController:

 MyViewController *myViewController = [[MyViewController alloc] init];
[self.navigationController presentModalViewController:myViewController animated:YES];

Anyone has encountered this problem?

Thanks!

jkigel
  • 1,592
  • 6
  • 28
  • 49

3 Answers3

2

You're doing much of the correct code, but not all in the correct places. You're correct that a UINavController should be initialized with a view controller. However, in the code you sent, MainViewController's init method is complete before the nav controller is initialized.

This is due to the fact that you really shouldn't be having the MainViewController decide when to present itself. It should be initialized and presented by something outside itself - the AppDelegate, in this case.

AppDelegate:

MainViewController *mvc = [[MainViewController alloc] init];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
self.window.rootViewController = self.navigationController;

If you then need MainViewController to present something modally, you should do it in viewWillAppear: or viewDidLoad:, not in its init method. Alternatively, create a public method on MainViewController (showMyModal) that the app delegate can call.

tooluser
  • 1,481
  • 15
  • 21
  • Where does it say any of this code is done in the init method (genuine question, I can't see any indication of where the second code sample actually is) – jrturton Nov 18 '12 at 18:32
  • The code in AppDelegate would be in whatever method you have defined that is calling the action. – tooluser Jan 06 '13 at 20:02
1

Create UINavigationController assign your viewcontroller to its root.

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: myViewController];
[self presentViewController:navController animated:YES completion:nil];
chongsj
  • 25
  • 1
  • 6
0

A UIViewController may not have a UINavigationController.
The navigation controller owns some controller only if you set it expicitly:

[yourNavController setViewControllers: @[ yourViewController1, ... , yourViewControllerN] ];
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187