NSDocument打开默认文档

时间:2015-12-28 16:37:19

标签: swift nsdocument

我正在Swift中编写一个基于NSDocument的应用程序。如果应用程序没有使用文档参数启动,我已将其设置为打开默认文档。

我注意到,如果我启动应用程序然后立即打开另一个文档,比如使用Open或Recent,则无标题的默认文档仍然存在,即使它未受影响。

我的印象是,在此工作流程中,Untitled文档被视为“意外”,应予以删除。它是否正确?如果是这样,我应该手动删除此窗口,还是有一个我忽略的设置?

1 个答案:

答案 0 :(得分:1)

您描述的行为不是自动的。有关如何处理此情况的示例,请参阅开源TextEdit示例代码。具体而言,-[DocumentController replaceTransientDocument:]实施take a look

- (void)replaceTransientDocument:(NSArray *)documents {
    // Transient document must be replaced on the main thread, since it may undergo automatic display on the main thread.
    if ([NSThread isMainThread]) {
        NSDocument *transientDoc = [documents objectAtIndex:0], *doc = [documents objectAtIndex:1];
        NSArray *controllersToTransfer = [[transientDoc windowControllers] copy];
        NSEnumerator *controllerEnum = [controllersToTransfer objectEnumerator];
        NSWindowController *controller;

        [controllersToTransfer makeObjectsPerformSelector:@selector(retain)];

        while (controller = [controllerEnum nextObject]) {
            [doc addWindowController:controller];
            [transientDoc removeWindowController:controller];
        }
        [transientDoc close];

        [controllersToTransfer makeObjectsPerformSelector:@selector(release)];
        [controllersToTransfer release];

    // We replaced the value of the transient document with opened document, need to notify accessibility clients.
    for (NSLayoutManager *layoutManager in [[(Document *)doc textStorage] layoutManagers]) {
        for (NSTextContainer *textContainer in [layoutManager textContainers]) {
        NSTextView *textView = [textContainer textView];
        if (textView) NSAccessibilityPostNotification(textView, NSAccessibilityValueChangedNotification);
        }
    }

    } else {
        [self performSelectorOnMainThread:_cmd withObject:documents waitUntilDone:YES];
    }
}

如果您同时查看-openDocumentWithContentsOfURL:display:error:以及其他几个调用上述方法的地方,您将会很清楚如何更换“瞬态文档”(“无标题”文档)打开的文件。

我希望这会有所帮助。