Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Cocoa 如何打开上次自动保存的文档?_Cocoa - Fatal编程技术网

Cocoa 如何打开上次自动保存的文档?

Cocoa 如何打开上次自动保存的文档?,cocoa,Cocoa,当我的应用程序启动时,我希望自动打开上次保存的文档,而无需用户干预 我的计划是将上次保存的文件的位置保存到用户默认值中,可能是dataOfType 我还将通过在我的应用程序控制器的应用程序shouldOpenUntitledFile中返回NO来阻止打开无标题文档 所以理论上这应该是可能的,但是怎么可能呢?如何以编程方式打开文档?我从Cocoa with Love中找到了这个答案 - (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)

当我的应用程序启动时,我希望自动打开上次保存的文档,而无需用户干预

我的计划是将上次保存的文件的位置保存到用户默认值中,可能是dataOfType

我还将通过在我的应用程序控制器的
应用程序shouldOpenUntitledFile
中返回NO来阻止打开无标题文档


所以理论上这应该是可能的,但是怎么可能呢?如何以编程方式打开文档?

我从Cocoa with Love中找到了这个答案

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    // On startup, when asked to open an untitled file, open the last opened
    // file instead
    if (!applicationHasStarted)
    {
        // Get the recent documents
        NSDocumentController *controller =
            [NSDocumentController sharedDocumentController];
        NSArray *documents = [controller recentDocumentURLs];

        // If there is a recent document, try to open it.
        if ([documents count] > 0)
        {
            NSError *error = nil;
            // point to last document saved
            NSInteger index = 0;
            [controller
                openDocumentWithContentsOfURL:[documents objectAtIndex:index]
                display:YES error:&error];

            // If there was no error, then prevent untitled from appearing.
            if (error == nil)
            {
                return NO;
            }
        }
    }

    return YES;
}
原始链接:

Swift 4示例:(代码进入应用程序代理)


上述解决方案解决了我的问题。我相信您的代码现在是错误的-CocoaWithLove代码按预期运行:它打开最后打开/保存的文档,而您的代码打开最旧的文档。也许这是你使用的OS X版本中的一个bug?你是对的,亚当。这是错误的。我想我一定是被我当时的观察误导了,不幸的是,今天我记不起细节了。最新版本的代码的索引设置为零,并且正如您所说的那样工作,但我不记得何时更改代码以及更改原因。应关闭/删除此问题,以免误导他人。你知道怎么做吗?我已经编辑了你的答案,改为使用0索引(我已经编辑了它以更正键入错误),如果其他人会对其进行同行审查,那就可以了。applicationHasStarted标志什么时候应该设置为true?在ApplicationIDFinishLaunching中?
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {

    let documentController = NSDocumentController.shared

    if let mostRecentDocument = documentController.recentDocumentURLs.first {
        documentController.openDocument(withContentsOf: mostRecentDocument, display: true, completionHandler: { (document, documentWasAlreadyOpen, errorWhileOpening) in
            // Handle opened document or error here
        })
        return false
    } else {
        return true
    }
}