我使用的是OpenPanel获取文件路径URL。这个作品:

[oPanel beginSheetModalForWindow:theWindow completionHandler:^(NSInteger returnCode)
{
 NSURL *pathToFile = nil;

 if (returnCode == NSOKButton)
     pathToFile = [[oPanel URLs] objectAtIndex:0];
}];

这不,从而导致错误的“只读变量的赋值”:

NSURL *pathToFile = nil;
[oPanel beginSheetModalForWindow:theWindow completionHandler:^(NSInteger returnCode)
{
 if (returnCode == NSOKButton)
     pathToFile = [[oPanel URLs] objectAtIndex:0];
}];
return pathToFile;

在一般情况下,任何企图从oPanel的上下文中提取pathToFile失败。这不是什么大不了的小状况,但我的代码的增长,我被迫的东西的一切 - XML解析,核心数据,等等 - 不适当区域内。我能做些什么来提取pathToFile?

感谢。

有帮助吗?

解决方案

  

这不,从而导致错误的“只读变量的赋值”:

NSURL *pathToFile = nil;
[oPanel beginSheetModalForWindow:theWindow completionHandler:^(NSInteger returnCode)
{
 if (returnCode == NSOKButton)
     pathToFile = [[oPanel URLs] objectAtIndex:0];
}];
return pathToFile;

是的,因为你想分配给pathToFile变量的副本创建块时被制成。你并没有使用原来的pathToFile变量,你块之外声明。

您可以使用__block关键字让块分配给这个变量,但我不认为这会帮助,因为beginSheetModalForWindow:completionHandler:不会阻塞。 (文档没有提到这一点,但没有理由方法块,并且可以与记录验证它没有。)消息立即返回,同时面板仍在运行。

所以,你想拥有你的完成处理程序块分配给一个局部变量,但在你声明的局部变量可能已被时间块运行回到你的方法,所以它不能够用值的工作,该块<德尔>左将离开在变量

不管你与pathToFile做应该是在块本身,或在方法(服用NSURL *参数),该块可以调用。

其他提示

您还可以runModal你开始表后你只需要确保您稍后结束薄片。这样,您就不必屈从于苹果的意志,它没有过时,它仍然应该很好地工作。

NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel beginSheetModalForWindow:window completionHandler:nil];
NSInteger result = [openPanel runModal];
NSURL *url = nil;
if (result == NSFileHandlingPanelOKButton) 
{
    url = [openPanel URL];
}
[NSApp endSheet:openPanel];

这似乎是黑魔法一点点的编码,但它确实工作。

scroll top