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

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...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值