NSFileManager fileExistsAtPath:isDirectory问题解决

3

有人可以帮我理解我在这个方法中做错了什么吗?

我正在尝试递归检测目录的内容并在每个目录中创建一个xml文件。非递归可以完美地工作并输出正确的xml文件。但递归在目录检测上出现问题,在“directories”元素下添加所有文件+目录。

_dirArray = [[NSMutableArray alloc] init];
_fileArray = [[NSMutableArray alloc] init];

NSError *error;
NSFileManager *filemgr = [NSFileManager defaultManager];
NSArray *filelist = [filemgr contentsOfDirectoryAtPath:dirPath error:&error];

for (int i = 0; i < filelist.count; i++)
{   
    BOOL isDir;
    NSString *file = [NSString stringWithFormat:@"%@", [filelist objectAtIndex:i]];
    [_pathToDirectoryTextField stringValue], [filelist objectAtIndex:i]];

    if ([filemgr fileExistsAtPath:dirPath isDirectory:&isDir] && isDir) // I think this is what is crapping out.
    {
        [_dirArray addObject:file];
    }
    else
    {
        if ([file hasPrefix:@"."])
        {
            // Ignore file.
        }
        else
        {
            [_fileArray addObject:file];
        }
    }
}

感谢大家提供的任何技巧。
1个回答

4

我可以看到这段代码来源于苹果文档中的示例,代码如下:if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir)。但是,如果你只是想获取目录或已删除的文件,那么把它复制过来并与else一起使用是一个非常糟糕的想法,因为它的意思是:

if (itexists and itsadirectory){
     //its a existing directory
     matches directories
}else{
    //it is not a directory or it does not exist
    matches files that were deleted since you got the listing 
}

这是我会做的方法:

NSString *dirPath = @"/Volumes/Storage/";

NSError *error;
NSFileManager *filemgr = [NSFileManager defaultManager];
NSArray *filelist = [filemgr contentsOfDirectoryAtPath:dirPath error:&error];

for (NSString *lastPathComponent in filelist) {
    if ([lastPathComponent hasPrefix:@"."]) continue; // Ignore file.
    NSString *fullPath = [dirPath stringByAppendingPathComponent:lastPathComponent];
    BOOL isDir;
    BOOL exists = [filemgr fileExistsAtPath:fullPath isDirectory:&isDir];

    if (exists) {
        if (isDir) {
            [_dirArray addObject:lastPathComponent];                
        }else{
            [_fileArray addObject:lastPathComponent];                
        }                    
    }
} 

实际上,我之前就是这样做的,但对我来说仍然不起作用。但如果你有信心它应该可以……那么也许我的问题出在别处。嗯。 - crewshin
不行。但无论如何,那是个好决定。我会保留它的。 - crewshin
啊,它们需要在不同的作用域中,如下所示 if (存在) { if (是目录) { } } - valexa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接