Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIViewController's navigationController is nil

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!

like image 637
jkigel Avatar asked Nov 17 '12 19:11

jkigel


2 Answers

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.

like image 86
tooluser Avatar answered Nov 08 '22 01:11

tooluser


Create UINavigationController assign your viewcontroller to its root.

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: myViewController];
[self presentViewController:navController animated:YES completion:nil];
like image 21
chongsj Avatar answered Nov 08 '22 01:11

chongsj