Search code examples
iosuiviewcontrolleruinavigationcontrolleruistoryboard

Navigation controller is always nil


I am presenting UIViewController like:

UIStoryboard *storyboard  = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

PhotoViewController *resultVC = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([PhotoViewController class])];
[self.navigationController presentViewController:resultVC animated:YES completion:^{}];

I have logged console and result is:

po self.navigationController
<UINavigationController: 0x9c3e920>

But when i am in PhotoViewController class i have logged console and result is :

po self.navigationController
nil

its nil here. i don't know why this happens. Also i have present with this one but its nil always :

[self presentViewController:resultVC animated:YES completion:^{}];

Solution

  • Yes, it is nil. UIViewController.navigationController property will only be set if the ViewController is pushed, not presented. A not-so-elegant solution is that you make a global reference(like put the reference in a singleton) to the NavigationController before you present it, then you can read it from inside your UIViewController.