I’m using an OpenPanel to get a file path URL. This works:
[oPanel beginSheetModalForWindow:theWindow completionHandler:^(NSInteger returnCode)
{
NSURL *pathToFile = nil;
if (returnCode == NSOKButton)
pathToFile = [[oPanel URLs] objectAtIndex:0];
}];
This doesn’t, resulting in an ‘assignment of read-only variable’ error:
NSURL *pathToFile = nil;
[oPanel beginSheetModalForWindow:theWindow completionHandler:^(NSInteger returnCode)
{
if (returnCode == NSOKButton)
pathToFile = [[oPanel URLs] objectAtIndex:0];
}];
return pathToFile;
In general, any attempt to extract pathToFile from the context of oPanel has failed. This isn’t such a big deal for small situations, but as my code grows, I’m forced to stuff everything — XML parsing, core data, etc — inside an inappropriate region. What can I do to extract pathToFile?
Thanks.
Yes, because you’re trying to assign to the copy of the
pathToFilevariable that gets made when the block is created. You’re not assigning to the originalpathToFilevariable that you declared outside the block.You could use the
__blockkeyword to let the block assign to this variable, but I don’t think this will help becausebeginSheetModalForWindow:completionHandler:doesn’t block. (The documentation doesn’t mention this, but there’s no reason for the method to block, and you can verify with logging that it doesn’t.) The message returns immediately, while the panel is still running.So, you’re trying to have your completion-handler block assign to a local variable, but your method in which you declared the local variable will probably have returned by the time block runs, so it won’t be able to work with the value that the block
leftwill leave in the variable.Whatever you do with
pathToFileshould be either in the block itself, or in a method (taking anNSURL *argument) that the block can call.