【问题标题】:How do I enumerate through a directory in Objective-C, and essentially clear out all the directories of non-directory files?如何枚举Objective-C中的目录,并从本质上清除所有非目录文件的目录?
【发布时间】:2013-07-12 05:11:36
【问题描述】:

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

【问题讨论】:

  • 具体来说,您遇到了什么问题? NSDirectoryEnumeratorNSFileManager 都有提供文件属性的方法,您可以从中测试目录状态。

标签: objective-c nsfilemanager


【解决方案1】:

这样的事情会起作用:

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

【讨论】:

  • 像这样使用enumeratorAtURL:... 比使用enumeratorAtPath: 更简单,因为enumeratorAtURL:... 返回绝对URL。 enumeratorAtPath: 返回相对路径,只有在枚举当前目录时才能直接传递给removeItemAtPath:error:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 2013-01-29
  • 2016-10-20
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 2015-01-20
相关资源
最近更新 更多