NSFileManager list directory contents excluding directories
cocoa, nsfilemanager, objective-c
Solution
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
Problem
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?