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

Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.

Chris Hulbert

(Comp Sci, Hons - UTS)

iOS Developer in Sydney.

I have worked at places such as Google, Cochlear, News Corp, Fox Sports, NineMSN, FetchTV, Woolworths, and Westpac, among others. If you're looking for a good iOS developer, drop me a line!

Get in touch:
[email protected]
github.com/chrishulbert
linkedin
my resume



 Subscribe via RSS