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

扶醉桌前 提交于 2020-02-03 02:10:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!