问题
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?
回答1:
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];
}
}
来源:https://stackoverflow.com/questions/17635586/how-do-i-enumerate-through-a-directory-in-objective-c-and-essentially-clear-out