spa*_*guy 4 cocoa asynchronous nsopenpanel objective-c-blocks
我正在使用OpenPanel来获取文件路径URL.这有效:
[oPanel beginSheetModalForWindow:theWindow completionHandler:^(NSInteger returnCode)
{
NSURL *pathToFile = nil;
if (returnCode == NSOKButton)
pathToFile = [[oPanel URLs] objectAtIndex:0];
}];
Run Code Online (Sandbox Code Playgroud)
这不会导致"只读变量的赋值"错误:
NSURL *pathToFile = nil;
[oPanel beginSheetModalForWindow:theWindow completionHandler:^(NSInteger returnCode)
{
if (returnCode == NSOKButton)
pathToFile = [[oPanel URLs] objectAtIndex:0];
}];
return pathToFile;
Run Code Online (Sandbox Code Playgroud)
通常,任何从oPanel上下文中提取pathToFile的尝试都失败了.对于小情况来说,这不是什么大问题,但随着我的代码的增长,我不得不在不适当的区域内填充所有内容 - XML解析,核心数据等.我该怎么做才能提取pathToFile?
谢谢.
这不会导致"只读变量的赋值"错误:
Run Code Online (Sandbox Code Playgroud)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 *块可以调用的方法(带参数)中.
| 归档时间: |
|
| 查看次数: |
5946 次 |
| 最近记录: |