Deep-enumerating a directory on the iphone, getting file attributes as you go
I found out the hard way, after lots of time wasted then a bit of googling, that NSFileManager’s enumeratorAtURL crashes! Don’t use it.
So if you need to recursively search a folder in objective-c (on the iPhone, in my case), grabbing all the attributes of the files (such as last-modified date), here’s an alternative way to do it. Please note this example uses ConciseKit:
NSMutableSet* pathsToSearch = $mset($.documentPath);
while (pathsToSearch.count) {
// Pop a path to search
NSString* pathToSearch = [pathsToSearch anyObject];
[pathsToSearch removeObject:pathToSearch];
// Scan it
NSArray* contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathToSearch error:nil];
for (NSString* item in contents) {
// Item is a file or a folder
NSString* itemPath = [pathToSearch stringByAppendingPathComponent:item]; // Get the full path for it
// Get the attributes
NSDictionary* attribs = [[NSFileManager defaultManager] attributesOfItemAtPath:itemPath error:nil];
BOOL isDirectory = $eql([attribs $for:NSFileType], NSFileTypeDirectory);
BOOL isFile = $eql([attribs $for:NSFileType], NSFileTypeRegular);
NSDate* modified = [attribs $for:NSFileModificationDate];
// Recurse if its a folder
if (isDirectory) {
[pathsToSearch addObject:itemPath];
}
// Do something with it
NSLog(@"%@; %@", itemPath, modified);
}
}