Getting the URL from beginSheetModalForWindow:

I use OpenPanel to get the URL of the file path. It works:

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

This does not result in a read-only variable assignment 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 oPanel context failed. This is not such a big problem for small situations, but as my code grows, I have to type everything - parsing XML, basic data, etc. - inside an unacceptable region. What can I do to extract pathToFile?

Thanks.

+4
source share
2 answers

This does not result in a read-only variable assignment error:

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

Yes, because you are trying to assign a copy to the pathToFile variable that is created when the block is created. You do not assign the original variable pathToFile that you declared outside the block.

You can use the __block keyword so that the block __block this variable, but I don’t think it will help, because beginSheetModalForWindow:completionHandler: not blocked. (This is not mentioned in the documentation, but there is no reason to block the method, and you can check with a log that this is not so.) The message is returned immediately while the panel is still working.

So, you are trying to assign a handler-completion block to a local variable, but your method in which you declared a local variable will probably be returned by running the temporary block, so it will not be able to work with the value that remains in the variable left .

Whatever you do with pathToFile , there must be either in the block itself or in the method (taking the argument NSURL * ) that the block can call.

+6
source

you can also start Modal after you run the sheet that you need to make sure you finish the sheet later. Thus, you do not need to lean toward the apple will, it is not outdated, and it should work perfectly.

 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]; 

It seems a bit like coding for black magic, but it works.

+1
source

Source: https://habr.com/ru/post/1300011/


All Articles