您的位置:首页 > 移动开发 > IOS开发

ios开发系列之使用NSDirectoryEnumerator的对象获得目录的资源列表

2015-10-27 17:28 821 查看
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...
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: