使用NSDocument打开任何文件夹

MrT*_*rTJ 4 cocoa file-type objective-c nsdocument

我试图编写一个应用程序,可以打开NSDocument子类中的任何文件夹,但无法找出正确的Info.plist设置.重要的是我的应用程序不应该使用捆绑包,也不应该使用具有特定文件扩展名的文件夹,只能打开任何文件夹.

我尝试了什么:

  • 如果我将文档类型扩展名设置为空字符串,则文件打开面板不允许选择任何文件
  • 如果我将文档类型扩展名设置为*,那么文件打开面板会启用所有文件但不启用文件夹:文件夹打开,如在finder中
  • 如果我将文件夹扩展名设置为文档类型扩展名,我可以将文件打开对话框中的文件夹作为文档打开(这是我想要的)但我将我的解决方案限制为具有该扩展名的文件夹
  • 通过将OSType设置为"fold",文档类型标识符或名称为"public.folder"等,因为我在论坛中读到的对我没有明显的效果.

如何在打开的文件对话框中打开任何文件夹?

MrT*_*rTJ 6

为了完整起见,这里有一些关于@ iKenndac答案的更多细节:

在IB中,检查First Responder的哪个方法与File/Open ...菜单项相关联.就我而言openDocument:.在AppDelegate中实现此方法:

-(void)openDocument:(id)sender
{
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setCanChooseFiles:NO];
    [panel setCanChooseDirectories:YES];
    [panel setAllowsMultipleSelection:NO];

    [panel beginSheetModalForWindow:nil
                  completionHandler:^(NSInteger result) {
                      if (result == NSFileHandlingPanelOKButton) {
                          NSURL* selectedURL = [[panel URLs] objectAtIndex:0];
                          NSLog(@"selected URL: %@", selectedURL);
                          NSError* error = nil;
                          [[NSDocumentController sharedDocumentController] 
                              openDocumentWithContentsOfURL:selectedURL 
                                                   display:YES 
                                                     error:&error];
                      }
                  }];
}
Run Code Online (Sandbox Code Playgroud)

您仍需要在Info.plist中定义文档类型,将标识符(LSItemContentTypes)字段设置为public.folder.


iKe*_*dac 3

如果不编写一些自定义代码,您可能无法做到这一点。

您需要NSOpenPanel手动呈现,如下所示:

NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setCanChooseFiles:NO];
[panel setCanChooseDirectories:YES];

[panel beginSheetForDirectory:nil
                         file:nil
               modalForWindow:[self window]
                modalDelegate:self
               didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
                  contextInfo:nil];
Run Code Online (Sandbox Code Playgroud)

以这种方式呈现的开放面板将允许用户选择他们想要的任何目录。您可以实现NSOpenPanel的委托方法来验证每个文件夹,并根据需要启用/禁用。