【问题标题】:How to acquire a file path using objective c如何使用objective c获取文件路径
【发布时间】:2018-02-14 12:55:35
【问题描述】:

我想要一个函数,它只返回在 finder 中选择的文件的完整文件路径。

我目前有这个功能:

+ (NSString*)choosePathWindow:(NSString*)title buttonTitle:(NSString*)buttonTitle allowDir:(BOOL)dir allowFile:(BOOL)file{
    [NSApp activateIgnoringOtherApps:YES];

    NSOpenPanel *openPanel = [NSOpenPanel openPanel];
    [openPanel setLevel:NSFloatingWindowLevel];
    [openPanel setAllowsMultipleSelection:NO];
    [openPanel setCanChooseDirectories:dir];
    [openPanel setCanCreateDirectories:dir];
    [openPanel setCanChooseFiles:file];
    [openPanel setMessage:title];
    [openPanel setPrompt:buttonTitle];

    NSString* fileName = nil;
    if ([openPanel runModal] == NSModalResponseOK)
    {
        for( NSURL* URL in [openPanel URLs])
        {
            fileName = [URL path];
        }
    }
    [openPanel close];
    return fileName;
}

但这通常表现得非常糟糕并且结结巴巴地进入视野并且在选择文件后经常挂起(我有一个 i7-7700k 和 16GB ddr4)并且在单击取消时总是挂起。我也相信这可能与我拥有的外部网络挂载有关。但是任何其他软件(例如 PHPStorm 或 Chrome)都可以在同一窗口中正常工作。

有没有更好的方法来做到这一点?

【问题讨论】:

  • NSOpenPanel *openPanel = [[NSOpenPanel alloc] init] 更改为 NSOpenPanel *openPanel = [NSOpenPanel openPanel]; 我认为可能对窗口的显示有所帮助,但在选择后仍会挂起。
  • 你为什么要[NSApp activateIgnoringOtherApps:YES][openPanel setLevel:NSFloatingWindowLevel][openPanel setCanCreateDirectories:dir];
  • 来自菜单栏应用程序(1,2)。因为我希望能够创建一个目录(路径)(3)
  • 你能发布崩溃日志或回溯吗?选择文件/目录后你的应用程序会做什么,你能发布应用程序崩溃的代码吗?
  • @Willeke 我再也不能让它崩溃了。我只能重现它挂着。现在将发布代码。

标签: objective-c nsopenpanel


【解决方案1】:

代码看起来不错。尝试从主线程调用你的函数;模态对话框需要这个并且通常不会自己强制执行。无论如何,Powebox(在沙盒中运行 NSOpenPanel 的东西)有点像野兽。此外,使用直接从 Xcode 启动的调试构建(不太好)和从 Finder 启动的发布构建,您可能会得到不同的结果。

要测试 NSOpenPanel:尝试在访客帐户下运行您的应用程序,以消除所有在沙盒中造成混乱的东西。

【讨论】:

    【解决方案2】:

    我的代码: (实际上在生产中:)

    -(void)OpenIt {
        NSOpenPanel* panel = [NSOpenPanel openPanel];
    
        // This method displays the panel and returns immediately.
        // The completion handler is called when the user selects an
        // item or cancels the panel.
    
        [panel setTitle: "title...."];
        NSString *title = NSLocalizedString(@"CHOOSE_FILE", @"");
        [panel setMessage: title];
    
        [panel beginWithCompletionHandler:^(NSInteger result){
            if (result == NSFileHandlingPanelOKButton) {
                NSURL*  theDoc = [[panel URLs] objectAtIndex:0];
                NSLog(@"%@", theDoc);
                // Open  the document using url
                [self openUsingURL: theDoc];
            }
        }];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 2014-10-15
      • 2010-10-14
      • 2016-06-06
      相关资源
      最近更新 更多