如何枚举Objective-C中的目录,并基本上清除非目录文件的所有目录? [英] How do I enumerate through a directory in Objective-C, and essentially clear out all the directories of non-directory files?

查看:46
本文介绍了如何枚举Objective-C中的目录,并基本上清除非目录文件的所有目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何遍历文件夹(包含可能包含更多子目录的子目录)并删除不是目录的文件?本质上,我问的是如何清除所有目录.在这方面,我在使用 enumeratorAtPath: 方法时遇到了一些麻烦,因为我不确定如何询问枚举器当前文件是否为目录.是否需要查看 fileAttributes 字典.注意:这对我来说可能是非常错误的,但是我使用路径的 NSString 初始化了枚举器.这会改变什么吗?

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?

推荐答案

这样的事情会起作用:

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

这篇关于如何枚举Objective-C中的目录,并基本上清除非目录文件的所有目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆