Simon Ayzman
Simon Ayzman

Reputation: 257

How do I enumerate through a directory in Objective-C, and essentially clear out all the directories of non-directory files?

How do I iterate through a folder (with subdirectories that might have further subdirectories in them) and delete the file if it's not a directory? Essentially, I'm asking how to clear all the directories. I'm having a little trouble with the enumeratorAtPath: method in this regard, because I'm not sure how to ask the enumerator if the current file is a directory or not. Does require looking through the fileAttributes dictionary. Note: This may be very wrong of me, but I initialize the enumerator with an NSString of the path. Does this change anything?

Upvotes: 0

Views: 3856

Answers (1)

rmaddy
rmaddy

Reputation: 318904

Something like this will work:

NSURL *rootURL = ... // File URL of the root directory you need
NSFileManager *fm = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnumerator = [fm enumeratorAtURL:rootURL
                    includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                    options:NSDirectoryEnumerationSkipsHiddenFiles
                    errorHandler:nil];

for (NSURL *url in dirEnumerator) {
    NSNumber *isDirectory;
    [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
    if (![isDirectory boolValue]) {
        // This is a file - remove it
        [fm removeItemAtURL:url error:NULL];
    }
}

Upvotes: 7

Related Questions