NSOpenPanel的setDirectoryURL不起作用

Tib*_*abo 3 macos cocoa objective-c

我正在尝试使用NSOpenPanel的新方法并设置其初始目录.问题是它只在第一次工作,然后它只是"记住"最后选择的文件夹,我不想要.我必须使用折旧的runModalForDirectory:file:使它工作.它不太理想,因为它被弃用了10.6,但幸运的是它仍适用于Lion.

我的代码是:

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"]];
Run Code Online (Sandbox Code Playgroud)

mip*_*adi 7

有几件事需要研究:

  1. ~/Pictures不是有效的URL.file:///Users/user/Pictures是.-[NSURL URLWithString:]需要有效的URL.您可能想要使用-[NSURL fileURLWithPath:].它会/Users/user/Pictures变成file:///Users/user/Pictures.
  2. Tildes不会自动展开,因此您希望使用它[@"~/Pictures stringByExpandingTildeInPath]来获取实际的文件路径.

放在一起,将最后一行更改为:

[panel setDirectoryURL:[NSURL fileURLWithPath:[@"~/Pictures" stringByExpandingTildeInPath]]];
Run Code Online (Sandbox Code Playgroud)

我认为这应该有效.