NSOpenPanel选择目录(不是文件)

时间:2012-07-18 07:43:41

标签: objective-c macos cocoa

我想让用户选择保存文件的目录。但是如何确保网址不是文件?

NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:YES];
[panel setCanCreateDirectories:YES];

[panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
    if (result == NSFileHandlingPanelOKButton) {
        NSArray* urls = [panel URLs];
        for (NSURL *url in urls) {
            //here how to judge the url is a directory or a file
        }
    }
}];

3 个答案:

答案 0 :(得分:22)

将来阅读此内容的任何人的更新:

在Swift中,使用

可以避免检查所选路径是否为文件
panel.canChooseFiles = false

答案 1 :(得分:5)

// First, check if the URL is a file URL, as opposed to a web address, etc.
if (url.isFileURL) {
  BOOL isDir = NO;
  // Verify that the file exists 
  // and is indeed a directory (isDirectory is an out parameter)
  if ([[NSFileManager defaultManager] fileExistsAtPath: url.path isDirectory: &isDir]
      && isDir) {
    // Here you can be certain the url exists and is a directory
  }
}

答案 2 :(得分:0)

Swift 4 版本:

if (url.isFileURL) {
    var isDir: ObjCBool = false
    if (FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir)) { 
       if isDir.boolValue {
                            print("It's a Directory path")
                          } else {
                            print("It's a file path")
                        }
                    }
}