从NSOpenPanel对话框中获取文件名

时间:2015-02-06 11:41:22

标签: objective-c cocoa xcode6

自从我上次与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);
}

(缩进已在帖子中搞砸,但在代码中是正确的)

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

造成这种情况的原因是什么?

感谢。

2 个答案:

答案 0 :(得分:0)

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

也许

[openPanel runModal]

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

答案 1 :(得分:0)

我一年前写的东西使用了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贬低了显而易见的容易,并以更高的复杂性取而代之。

相关问题