NSFileManager fileExistsAtPath: проблема isDirectory - PullRequest
2 голосов
/ 29 февраля 2012

Может кто-нибудь помочь мне понять, что я делаю не так с этим методом?

Я пытаюсь рекурсивно определить содержимое каталогов и создать XML-файл в каждом из них. Нерекурсивный работает отлично и выводит правильные файлы XML. Рекурсивные дроссели при обнаружении dir и добавление всех файлов + dir в элементе "directoryies".

_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 голосов
/ 29 февраля 2012

я вижу "if ([fileManager fileExistsAtPath: fontPath isDirectory: & isDir] && isDir)", исходя из примеров Apple в документации, но копировать его по частям и использовать с другим - очень плохая идея, если только вы не хотите получитькаталоги или удаленные файлы, потому что это означает:

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];                
        }                    
    }
} 
...