几乎直接来自文档:
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
NSString *file;
while (file = [dirEnum nextObject]) {
if ([[file pathExtension] isEqualToString: @"jpg"]) {
// process the document
[self doSomethingWithFile: [docsDir stringByAppendingPathComponent:file]];
}
}
看起来 NSDirectoryEnumerator 也支持快速枚举,所以你可以使用它:
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
for (NSString *file in dirEnum) {
if ([[file pathExtension] isEqualToString: @"doc"]) {
// process the document
[self doSomethingWithFile: [docsDir stringByAppendingPathComponent:file]];
}
}
使用目录枚举器和遍历返回的列表之间的区别在于-contentsOfDirectoryAtPath:
,目录枚举器还将提供来自子目录的结果。