简体   繁体   中英

NSOpenPanel's setDirectoryURL doesn't work

I'm trying to use the new methods for NSOpenPanel and set its initial directory. The problem is that it only works at the first time and after that it just "remembers" the last selected folder, which I don't want. I have to use the depreciated runModalForDirectory:file: to make it work. It's less than ideal because it was deprecated at 10.6, but thankfully it still works on Lion.

My code is:

NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setAllowedFileTypes:[NSArray arrayWithObjects: @"jpg",@"JPG",@"png", nil]];
panel.canChooseDirectories = YES;
panel.allowsMultipleSelection = YES;
handler = ^(NSInteger result) {stuff};
[panel setDirectoryURL:[NSURL URLWithString:@"/Library/Desktop Pictures"]];

There are a couple things to look into:

  1. ~/Pictures is not a valid URL. file:///Users/user/Pictures is. -[NSURL URLWithString:] requires a valid URL. You probably want to use -[NSURL fileURLWithPath:] instead. It will turn /Users/user/Pictures into file:///Users/user/Pictures .
  2. Tildes are not automatically expanded, so you want to use [@"~/Pictures stringByExpandingTildeInPath] to get an actual file path.

Put together, change the last line to:

[panel setDirectoryURL:[NSURL fileURLWithPath:[@"~/Pictures" stringByExpandingTildeInPath]]];

I think that should work.

The panel in Lion expects an URL like: file://localhost/Library/Desktop Pictures, but your URL starts with the actual path. Use [NSURL fileURLWithPath:@"/Library/Desktop Pictures"] instead.

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM