添加UINavigation控制器时出现'NSInvalidArgumentException'

时间:2014-01-16 09:22:15

标签: ios objective-c cocoa-touch

我正在尝试添加一个静态UINavigation栏,它将出现在我项目中的几乎所有ViewControllers上。 UINavigation栏将始终具有相同的3个按钮(一个打开侧面菜单,一个打开搜索,一个打开ViewController以允许更改设置。

我已经学过几个教程(没有一个是针对Xcode5 / iOS7的),这些对我来说没有用。

“AppDelegate.m”的相关代码:

#import "AppDelegate.h"
#import "MainViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{   
    UINavigationController *navVC = [[UINavigationController alloc] init];

    MainViewController *mainVC = [[MainViewController alloc] init];

    [navVC setViewControllers:[NSArray arrayWithObject:mainVC]];

    [self.window setRootViewController:navVC];

    return YES;
}

运行此命令会出现以下错误:

'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

MainViewController.m init

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

谢谢,

编辑:

要澄清,我正在使用一个名为'Main'的故事板,许多ViewControllers正在加载名为'MainVC'的第一个,它有一个名为'MainViewController'的自定义类。感谢@LML现在的工作代码是:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"
                                                         bundle: nil];
    MainViewController* mainVC = [mainStoryboard instantiateInitialViewController];
    UINavigationController *navVC =[[UINavigationController alloc]       initWithRootViewController:mainVC];
    [self.window setRootViewController:navVC];
    [_window makeKeyAndVisible];
    return YES;
}

3 个答案:

答案 0 :(得分:1)

使用此功能,因为您使用的是故事板

-

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:...{   

// set to storyboard on launch
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"iPhoneStoryboard"
                                                         bundle: nil];

MainViewController* mainVC = [mainStoryboard instantiateInitialViewController];
UINavigationController *navVC =[[UINavigationController alloc]    initWithRootViewController:mainVC];
[self.window setRootViewController:navVC];
 [window makeKeyAndVisible];
 return YES;
 }

答案 1 :(得分:0)

使用[[UINavigationController alloc] initWithRootViewController:mainVC]

答案 2 :(得分:0)

didFinishLaunchingWithOptions方法

中试试这个
MainViewController *mainVC = [MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];

UINavigationController *navVC =[[UINavigationController alloc] initWithRootViewController:mainVC]; // Change here
[navVC setViewControllers:[NSArray arrayWithObject:mainVC]]; 
[self.window setRootViewController:navVC];

return YES;