NSDirectoryEnumerator
,目录枚举类,一个NSDirectoryEnumerator
对象列举了一个目录的内容,返回的所有文件在目录中的路径名,在该目录中。这些路径是相对于目录而言的。
enumeratorAtPath:
这个方法一次可以枚举指定目录中的每一个文件. 默认情况下,如果其中一个文件为包含子文件,那么也会递归的枚举它的子文件. 该方法返回一个目录的所有资源列表.
下面以app所在路径为例取得以mp3
为后缀的文件名和文件路径
// 类NSBundle
的对象是一个目录,其中包含了程序会使用到的资源. 这些资源包含了如图像,声音,编译好的代码,nib
文件(用户也会把bundle
称为plug-in
).
NSFileManager * fileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator * myDirectoryEnumerator = [fileManager enumeratorAtPath:[NSBundle mainBundle].bundlePath];
NSMutableArray * filePathArray = [[NSMutableArray alloc]init];//存放文件路径数组
NSMutableArray * fileNameArray = [[NSMutableArray alloc]init];//存放文件名数组
NSString * file;//声明文件名
while (file = [myDirectoryEnumerator nextObject]) {
if ([file.pathExtension isEqualToString:@"mp3"]) { //判断file的后缀名是否为mp3
[filePathArray addObject:[self bundlePath:file]];
[fileNameArray addObject:file];
}
}
- (NSString *)bundlePath:(NSString *)fileName{
return [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:fileName];
}
nextObject
方法返回集合中下一个枚举对象, 当所有对象都被枚举完了,则返回nil
;
NSArray *anArray = // ... ;
NSEnumerator *enumerator = [anArray objectEnumerator];
id object;
while ((object = [enumerator nextObject])) {
// do something with object...
}