从 NSOpenPanel 对话框获取文件名

Getting filename from NSOpenPanel dialog

我上次玩 Cocoa 已经一年了,似乎发生了很多变化。

我正在尝试 运行 打开对话框并检索文件路径。这曾经很简单,但现在...

密码是:

-(NSString *)getFileName{
NSOpenPanel* panel = [NSOpenPanel openPanel];
__block NSString *returnedFileName;

// This method displays the panel and returns immediately.
// The completion handler is called when the user selects an
// item or cancels the panel.
[panel beginWithCompletionHandler:^(NSInteger result){
    if (result == NSFileHandlingPanelOKButton) {
        NSURL* theDoc = [[panel URLs] objectAtIndex:0];

        // Open  the document.
        returnedFileName = [theDoc absoluteString];
    }
}];
return returnedFileName;
}

-(IBAction)openAFile:(id)sender{

NSLog(@"openFile Pressed");

NSString* fileName = [self getFileName];

NSLog(@"The file is: %@", fileName);
}

(缩进在 post 中被搞砸了,但在代码中是正确的)

我的问题是打开的对话框一打开就执行最后的 NSLog 语句,而不是等到对话框关闭。这使得 fileName 变量为 null,这是最终 NSLog 报告的内容。

这是什么原因造成的?

谢谢。

有人问你类似的问题: How do I make my program wait for NSOpenPanel to close?

也许

[openPanel runModal]

对你有帮助。它一直等到用户关闭面板

我一年前写的东西使用了 runModal,所以根据 Christoph 的建议我又回到了那个。

beginWithCompletionHandler 块似乎是不必要的,至少在这种情况下是这样。删除它还具有消除使用 __block 标识符的必要性的优点。

以下内容现在可以按要求工作了

-(NSString *)getFileName{
    NSOpenPanel* panel = [NSOpenPanel openPanel];
    NSString *returnedFileName;

    // This method displays the panel and returns immediately.
    // The completion handler is called when the user selects an
    // item or cancels the panel.

    if ([panel runModal] == NSModalResponseOK) {
        NSURL* theDoc = [[panel URLs] objectAtIndex:0];

        // Open  the document.
        returnedFileName = [theDoc absoluteString];
    }

return returnedFileName;
}

干得好 Apple 弃用了显而易见和简单的东西并用增加的复杂性取而代之。