从NSOpenPanel对话框获取文件名
问题描述:
自从我上一次使用Cocoa已经过去了一年,似乎很多变化。从NSOpenPanel对话框获取文件名
我想运行一个打开的对话框并检索文件路径。过去,这是很简单的,但现在......
的代码是:
-(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报告的内容。
这是什么造成的?
谢谢。
答
有一个类似的问题对你的: 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;
}
,做得很好苹果弃用明显,容易与增加的复杂性取代它。
谢谢克里斯托弗。结合一些修剪,我认为是苹果部分的代码膨胀,对它进行排序。 – 2015-02-06 12:12:45