简单 Cocoa 应用 ViewController

Simple Cocoa App with ViewController

我正在尝试创建自定义 NSViewController 并在 viewDidLoad 中注销一些内容。在 iOS 中,这非常简单并且工作正常。但是,当我在 NSWindow 上设置 contentViewController 时(我假设它类似于 iOS 中的 RootViewController?),它会尝试从笔尖加载它。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {


   self.ABViewController = [[ABViewController alloc] init];

   self.window.contentViewController = self.ABViewController;


}

2016-06-28 09:15:42.186 TestApp[32103:33742217] -[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: ABViewController in bundle (null).

关于 Cocoa 与 iOS 的区别,我遗漏了哪些让我无法简单地设置 viewController 的假设?

您的程序似乎找不到定义视图的文件。你需要为故事板做这样的事情:

UIStoryboard *sboard = [UIStoryboard storyboardWithName:@"StoryboardFileName" 
                                             bundle:NSBundle.mainBundle()];
SecondViewController *vc1 = [sboard instantiateInitialViewController];

NSViewControllerUIViewController 的行为不同,因为它不会自动知道要查找与自身同名的 nib 文件。换句话说,它不会自动知道要查找 ABViewController.nib 文件。

解决此问题的最简单方法是重写 ABViewController 中的 nibName 方法:

@implementation ABViewController

- (NSString *)nibName {
    return NSStringFromClass([self class]);
}

@end

请注意,使用 NSStringFromClass() 通常比尝试对字符串进行硬编码要好,因为这种方式可以在重构后继续存在。

然后您可以像以前一样调用 [[ABViewController alloc] init];NSViewController 的默认 init 方法将从您覆盖的 nibName 方法中获取笔尖名称。