推送ViewController时navigationController为nil的技术问题求助
It looks like the root of your problem is that your MainViewController isn’t properly embedded within a UINavigationController as the window’s root view controller. Let’s break down how to fix this:
Root Cause
From your code snippet, you initialize MainViewController but likely don’t wrap it in a UINavigationController before setting it as the window’s root. Without this, any calls to self.navigationController from MainViewController will return nil because it’s not part of a navigation stack.
Corrected Implementation
Here’s how to properly set up your navigation controller in didFinishLaunchingWithOptions:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Initialize your main view controller MainViewController *mainVC = [[MainViewController alloc] init]; // Wrap it in a UINavigationController UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:mainVC]; // Set the navigation controller as the window's root view controller self.window.rootViewController = navigationController; // Make the window visible [self.window makeKeyAndVisible]; return YES; }
Key Points to Verify
- Ensure you’re setting the navigation controller (not the
MainViewControllerdirectly) as the window’srootViewController. - After this setup, when you call
[self.navigationController pushViewController:viewControllerB animated:YES];fromMainViewController,self.navigationControllerwill no longer benil. - Double-check that you haven’t accidentally omitted the
makeKeyAndVisiblecall, as this ensures the window displays properly.
If you’re still having issues, confirm you’re not presenting MainViewController modally elsewhere (instead of using it as the root)—this would also cause navigationController to be nil.
内容的提问来源于stack exchange,提问作者Ran

