iPhone:NSFilemanager fileExistsAtPath:isDirectory:无法正常工作?

时间:2009-07-28 21:35:45

标签: iphone objective-c nsfilemanager

我正在开发一款适用于越狱iPhone的应用程序。我正在尝试只获取文件夹的目录。所以我这样做:

NSArray *contentOfFolder = [[NSFileManager defaultManager] directoryContentsAtPath:path];
NSLog(@"contentOfFolder: %@", contentOfFolder);
directoriesOfFolder = [[NSMutableArray alloc] initWithCapacity:100];
for (NSString *aPath in contentOfFolder) {
    NSLog(@"apath: %@", aPath);

    BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:aPath isDirectory:&isDir] &&isDir)
    {
        [directoriesOfFolder addObject:aPath];
        NSLog(@"directoriesOfFolder %@", directoriesOfFolder);
    }
}
NSLog(@"dirctories %@", directoriesOfFolder);

但看看我得到了什么。当我得到文件夹的内容时,一切看起来都很好:

2009-07-28 23:23:35.930 Drowser [573:207] new path / private / var 2009-07-28 23:23:35.945 Drowser [573:207] contentOfFolder :(     钥匙扣,     “管理偏好”,     移动设备,     备份,     缓存,     D b,     EA,     空,     文件夹,     LIB,     本地,     锁,     日志,     日志,     移动,     封邮件,     喜好,     根,     跑,     阀芯,     藏,     TMP,     VM )

然后:

2009-07-28 23:23:35.950 Drowser [573:207] apath:Keychains 2009-07-28 23:23:35.954 Drowser [573:207] apath:管理偏好 2009-07-28 23:23:35.959 Drowser [573:207] apath:MobileDevice 2009-07-28 23:23:35.984 Drowser [573:207] apath:备份 2009-07-28 23:23:35.993 Drowser [573:207] apath:cache 2009-07-28 23:23:36.002 Drowser [573:207] apath:db 2009-07-28 23:23:36.011 Drowser [573:207] apath:ea 2009-07-28 23:23:36.019 Drowser [573:207] apath:空 2009-07-28 23:23:36.028 Drowser [573:207] apath:文件夹 2009-07-28 23:23:36.037 Drowser [573:207] apath:lib 2009-07-28 23:23:36.046 Drowser [573:207] directoriesOfFolder(     LIB )

只有“lib”!被识别为文件夹。怎么可能?其他人也是文件夹。我通过SSH确认了它。

有没有人有想法?我做错了吗?

1 个答案:

答案 0 :(得分:23)

这是一个非常容易犯的错误,但它也很容易修复。枚举目录的内容只会为您提供项目的名称,而不是项目的完整路径。你必须自己构建完整的路径。所以你在哪里:

for (NSString *aPath in contentOfFolder) {
  NSLog(@"apath: %@", aPath);

  BOOL isDir;
  if ([[NSFileManager defaultManager] fileExistsAtPath:aPath isDirectory:&isDir] &&isDir) {
    [directoriesOfFolder addObject:aPath];
    NSLog(@"directoriesOfFolder %@", directoriesOfFolder);
  }
}

你应该真的有这个:

for (NSString *aPath in contentOfFolder) {
  NSString * fullPath = [path stringByAppendingPathComponent:aPath];

  BOOL isDir;
  if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir] &&isDir) {
    [directoriesOfFolder addObject: fullPath];
  }
}