Search code examples
objective-cnsfilemanager

NSFileManager fileExistsAtPath:isDirectory issue


Can someone help me understand what I'm doing wrong with this method?

I'm trying to recursively detect the contents of directories and create an xml file in each one. Non-recursive works perfectly and outputs proper xml files. Recursive chokes on dir detection and add's all files + dir's under the "directories" element.

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

Thanks for any tips guys.


Solution

  • i can see "if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir)" coming from Apple's examples in the documentation but to copy it piecemeal and use it with else is a very bad idea unless you only want to get directories or deleted files because what it means is:

    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 
    }
    

    here is how i would do it:

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