基于文档的应用程序的“新建文档”停靠菜单项不会打开新文档

时间:2015-08-23 11:14:34

标签: objective-c cocoa nsdocument nsmenu nsdocumentcontroller

我的基于文档的应用程序有一个带有“新文档”项目的停靠菜单。停靠菜单在Interface Builder中生成,其项目的操作与'First Responder'-newDocument:

相关联

文档控制器是名为NSDocumentController的{​​{1}}的子类。

在app delegate中,此代码用于防止在启动时打开无标题文档(而是显示文档控制器的打开面板):

DocumentController

如果我现在启动我的应用程序,它将显示打开的面板而不是无标题文档。如果我然后单击停靠菜单的“新建文档”项,则不会打开新文档。如果单击模板主菜单中的标准文件菜单选项“新建文档”,则会打开一个新文档。

我想不出为什么会这样,是吗?如何让停靠菜单打开新文档?

编辑:Here is a sample project which has no NSDocumentController subclass but still has the same problem.

1 个答案:

答案 0 :(得分:1)

Menu item calls newDocument method on the document controller. If you click on the dock you trigger NSApplication stuff and it's delegate. E.g. if you have a existing app window than you will not get called there. No window will trigger applicationShouldOpenUntitledFile

In your document controller override like this:

- (id)openUntitledDocumentAndDisplay:(BOOL)displayDocument error:(NSError *__autoreleasing *)outError {
  [self openDocument:nil]
}

And instead of responding to appdelegate(should bla bla) do this if you want after launch to display openPanel. If you want to trigger it when user clicks on the icon then do the second method

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [(DocumentController *)[NSDocumentController sharedDocumentController] openDocument:nil];
}

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender {
    return YES;
}

The action of the File menu's New item in a document-based application. The default implementation of this method invokes -openUntitledDocumentAndDisplay:error: and, if nil is returned, presents the error in an application-modal panel.

  • (IBAction)newDocument:(id)sender;