Mac App:'自动加载'上次使用的文档

Zak*_*411 0 macos xcode cocoa objective-c

我目前正在编写基于文档的应用程序,并且很想知道如何在应用程序启动时默认加载最近使用的文档("文件>打开最近"部分)?有关此代码段或代码段的任何好消息吗?Obj-C的新成员

谢谢,扎克

Jon*_*son 7

在您的应用程序委托中,您需要实现applicationShouldOpenUntitledFile:

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

    return YES;
}
Run Code Online (Sandbox Code Playgroud)

显然,XCode中默认的基于NSDocument的cocoa应用程序没有AppDelegate.奇怪的.要添加一个:

  • 在Project中添加一个新类,称之为MyAppDelegate,或者你想要的任何东西.
  • 在MyAppDelegate的界面中,添加协议NSApplicationDelegate,它应该如下所示:

    @interface MyAppDelegate:NSObject <NSApplicationDelegate> {}

  • 打开MainMenu.xib

  • 将Object实例拖到xib的窗口,Object实例看起来像一个蓝色框.
  • 选择Object实例,然后在检查器中,转到Identity选项卡(蓝色i)
  • 将Class设置为MyAppDelegate
  • 在xib中选择"应用程序"
  • 在检查器中,单击"连接"选项卡(蓝色箭头图标)并从"委托"拖动到刚刚设置的应用程序委托.

你现在很高兴.

  • 答案是Jawngee回应的前四个字. (2认同)