#import<Foundation/Foundation.h> int main(int argc,const char *argv) { NSAutoreleasePool *pool ;//自动释放池 pool =[[NSAutoreleasePool alloc] init]; NSFileManager *manager; manager=[NSFileManager defaultManager];//defaultManager类方法 用来创建NSFileManager对象 NSString *home; //stringByExpandingTildeInPath将~替换成当前 用户的主目录在MAC中主目录是/Users/markd home=[@"~"stringByExpandingTildeInPath]; //enumeratorAtPath返回一个NSDictionaryEnumerator他是NSEnumerator子类 NSDirectoryEnumerator *direnum; direnum=[manager enumeratorAtPath:home]; NSMutableArray *files;//可变数组 files=[NSMutableArray arrayWithCapacity:42]; NSString *fileName; while(fileName=[direnum nextObject]){ if([[fileName pathExtension] isEqualTo:@"jpg"]){//pathExtension可以获取文件去除‘.’的后缀名 例如xx.jpg 获取jpg [files addObject:fileName]; } } NSEnumerator *fileEnum; fileEnum=[files objectEnumerator];//NSDirectoryEnumerator是NSEnumerator子类所以可以快速的把enumeratorAtPath的结果传递给快速枚举 while(fileName=[fileEnum nextObject]){ NSLog(@"%@",fileName); } [pool drain];//自动释放池 return 0;//程序成功退出 }
方法二:舍弃枚举变量
//方法2 舍弃两个枚举变量 int main(int argc,const char *argv) { NSAutoreleasePool *pool=[[NSAutorelease alloc] init]; NSFileManager *manager; manager =[NSFileManager defaultManager]; NSString *home; home=[@"~"stringByExpandingTildeInPath]; NSMutableArry *files; files=[NSMutableArray arrayWithCapacity:42]; for(NSString *fileName in [manager enumeratorAtPath:home]){ if([[fileName pathExtension] isEqualTo:@"jpg"]){ [files addObject:fileName]; } } for(NSString *fileName in files){ NSLog(@"%@",fileName); } }