Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFileManager list directory contents excluding directories

Is there a way to tell the -[NSFileManager contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:] method to exclude directory names when gathering the contents of a directory?

I have a tree view showing folders and want to show ONLY files in the table view, but I can't seem to find a key or any other way to exclude folders. I suppose I could iterate the returned array to stuff only files into a second array, which will be used as the data source, but this double-handling seems a bit dodgy.

I also tried returning nil from the tableView:viewForTableColumn:row: method if the NSURL was a directory, but that only results in a blank row in the table, so that's no good either.

Surely there is a way to just tell NSFileManager that I only want files?

like image 653
Rainier Wolfcastle Avatar asked Aug 03 '13 01:08

Rainier Wolfcastle


2 Answers

You can go a little deeper with a directory enumerator.

How about this?

NSDirectoryEnumerator *dirEnumerator = [localFileManager enumeratorAtURL:directoryToScan includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey,nil] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants  errorHandler:nil];
NSMutableArray *theArray=[NSMutableArray array];

for (NSURL *theURL in dirEnumerator) {

    // Retrieve the file name. From NSURLNameKey, cached during the enumeration.
    NSString *fileName;
    [theURL getResourceValue:&fileName forKey:NSURLNameKey error:NULL];

    // Retrieve whether a directory. From NSURLIsDirectoryKey, also
    // cached during the enumeration.

    NSNumber *isDirectory;
    [theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];


    if([isDirectory boolValue] == NO)
    {
        [theArray addObject: fileName];
    }
}

// theArray at this point contains all the filenames
like image 199
Michael Dautermann Avatar answered Jan 03 '23 14:01

Michael Dautermann


The best options is to use enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: to populate an array that excludes folders.

NSFileManager *fm = [[NSFileManager alloc] init];
NSDirectoryEnumerator *dirEnumerator = [fm enumeratorAtURL:directoryToScan
                    includingPropertiesForKeys:@[ NSURLNameKey, NSURLIsDirectoryKey ]
                    options:NSDirectoryEnumerationSkipsHiddenFiles | NSDirectoryEnumerationSkipsSubdirectoryDescendants
                    errorHandler:nil];

NSMutableArray *fileList = [NSMutableArray array];

for (NSURL *theURL in dirEnumerator) {
    NSNumber *isDirectory;
    [theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
    if (![isDirectory boolValue]) {
        [fileList addObject:theURL];
    }
}

This will give you an array of NSURL objects representing the files.

like image 44
rmaddy Avatar answered Jan 03 '23 16:01

rmaddy