Let's imagine you're about to throw a save panel as part of some export feature in your app. Because you love your customers, you've recorded the location they last exported to. So you want to pre-populate the save panel with that location for convenience. Here's an easy way:
However it comes with two nasty gotchas:
- If the folder turns out to no longer exist (maybe the document has been moved to a different computer, or the user's had a tidyup since last time) then the panel will look perfectly normal, displaying a perfectly reasonable alternate location. However, if the Save button is happily clicked without navigating elsewhere at all, you're in for a nasty surprise: the save panel will return back the URL you first fed into it, even though that's not onscreen, and no longer exists! So your export will fail
- If that directory URL turns out to actually be a file, then in a sandboxed app, the Powerbox has a nasty habit of being confused and not actually displaying the save panel
What is to be done? Time to spruce up our code a little:
This approach neatly checks if the folder exists and is actually a folder (if it doesn't exist, -getResourceValue:forKey:error: will return NO).
Slight followup: Looking back at the code, it crossed my mind that calling -getResourceValueForKey:… with NSURLParentDirectoryURLKey make quite a bit of sense. We inherently trust that API to fail if the parent isn't a directory. But if the URL you're testing happens not to exist, the call will fail also.