确定NSString中的路径是指向目录还是​​文件?

时间:2009-05-05 17:49:05

标签: objective-c cocoa file

我有一个包含路径的NSString,但它可以是文件或目录。

Cocoa中是否有等效的Python os.path.isdir()os.path.isfile()方法?

2 个答案:

答案 0 :(得分:45)

请参阅NSFileManager Class Reference

[[NSFileManager defaultManager] fileExistsAtPath:pathname 
                                isDirectory:&directoryFlag];

例如:

NSString *file = @"/tmp/";
BOOL isDir = NO;
if([[NSFileManager defaultManager]
     fileExistsAtPath:file isDirectory:&isDir] && isDir){
    NSLog(@"Is directory");
}

答案 1 :(得分:2)

如果来自htw的解决方案不起作用,请尝试:

NSString *file = @"/tmp/";
BOOL isDir
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:file];
while ((file = [dirEnum nextObject])) {
   [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir];
   if(isDir){
      NSLog(@"%@ is a directory", file);
   }
}