Mac OS:如何确定路径是文件还是目录

Dim*_*lov 3 filesystems macos file objective-c nsfilemanager

我有一条路径,我想知道,是这个目录还是一个文件.很简单,但我有一个问题.这是我的路径:

NSString *file = @"file://localhost/Users/myUser/myFolder/TestFolder/";
Run Code Online (Sandbox Code Playgroud)

要么

NSString *file = @"file://localhost/Users/myUser/myFolder/my_test_file.png";
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

BOOL isDir;


// the original code from apple documentation: 
// if ([fileManager fileExistsAtPath:file isDirectory:&isDir] && isDir)
// but even my if returns me "not ok" in log

if([[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir])
{

     NSLog(@"directory");
}
else
{
     NSLog(@"not ok");
}
Run Code Online (Sandbox Code Playgroud)

这个文件上的文件和目录都存在,它们没问题.但我认为问题可能在其中.但我不知道为什么.请帮帮我.

顺便说一下,我从另一种方法获得路径:

   NSArray *contentOfMyFolder = [[NSFileManager defaultManager]
                contentsOfDirectoryAtURL:urlFromBookmark
              includingPropertiesForKeys:@[NSURLContentModificationDateKey, NSURLLocalizedNameKey]
                                 options:NSDirectoryEnumerationSkipsHiddenFiles
                                   error:nil];
Run Code Online (Sandbox Code Playgroud)

在for循环之后,我得到存储在数组中的项目contentOfMyFolder 并获取如下所示的路径:

 for (id item in contentOfMyFolder) {
     NSString *path = [item absoluteString]; 
 }
Run Code Online (Sandbox Code Playgroud)

我认为这是方法的完美有效途径 fileExistsAtPath:(NSString *)path isDirectory:(BOOL)isDir

哪个问题可以隐藏?!

Mar*_*n R 6

问题出在这里:

NSString *path = [item absoluteString];
Run Code Online (Sandbox Code Playgroud)

因为这会创建URL的字符串表示形式,例如

file://localhost/Users/myUser/myFolder/TestFolder/
Run Code Online (Sandbox Code Playgroud)

这不是fileExistsAtPath:预期的.您需要的是path将URL转换为路径的方法:

for (NSURL *item in contentOfMyFolder) {
    NSString *path = [item path];
    BOOL isDir;
    if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
        if (isDir) {
            NSLog(@"%@ is a directory", path);
        } else {
            NSLog(@"%@ is a file", path);
        }
    } else {
        NSLog(@"Oops, %@ does not exist?", path);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以询问URL的"目录属性":

for (NSURL *item in contentOfMyFolder) {
    NSNumber *isDir;
    NSError *error;
    if ([item getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:&error]) {
        if ([isDir boolValue]) {
            NSLog(@"%@ is a directory", item);
        } else {
            NSLog(@"%@ is a file", item);
        }
    } else {
        NSLog(@"error: %@", error);
    }
}
Run Code Online (Sandbox Code Playgroud)