打开“新”文件?

时间:2011-02-09 02:08:58

标签: objective-c cocoa macos

我在myDocument.m文件中实现了一些代码,它只是尝试在启动时加载上次使用的文档。但是,从全新安装启动(或在删除最后使用的文件后运行)时,不会出现“新”文档窗口。有谁知道我的代码要添加什么来做到这一点?这是:

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    NSURL *lastURL=[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:lastURL display:YES error:nil];
    if (lastURL!=nil)
    {
     [docController openDocumentWithContentsOfURL:lastURL display:YES error:nil];    
        return NO;
    }

    return YES;
}

2 个答案:

答案 0 :(得分:1)

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    NSArray* urls = [[NSDocumentController sharedDocumentController] recentDocumentURLs];
    if ([urls count] > 0){
        NSURL *lastURL= [urls objectAtIndex: 0];

        if ([[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:lastURL display:YES error:nil]){
                   return NO;
             }      

    }

    return YES;
}

修改

我改变了它并尝试了它现在应该工作。

答案 1 :(得分:0)

什么是docController,为什么要发送-openDocumentWithContentsOfURL:display:error:两次?请注意,该方法返回文档而不是URL,因此使用返回值作为URL无论如何都不会起作用。

以下是更清晰的等效代码:

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    id lastDoc = [[NSDocumentController sharedDocumentController]
        openDocumentWithContentsOfURL:lastURL
        display:YES error:NULL];
    return (lastDoc == nil);
}

但是,它仍然无法解释您为何没有获得无标题文档。如果您注释掉-applicationShouldOpenUntitledFile:以便应用程序遵循标准Cocoa行为会发生什么?问题可能出在其他地方。

相关问题