IOS 递归简单使用及相关操作

来源:互联网 发布:英国优越教育 知乎 编辑:程序博客网 时间:2024/05/22 03:49

1递归,查找文件的方法怎么写,(查找当前路径下的所有文件的数量)步骤:

解决方案:1.创建一个查找文件的方法:带参数 ,   在方法中创建一个FlieManager对象 NSFileManager *fm = [NSFileManagerdefaultManager];

2.文件夹下面的内容是数组,所以在上行代码下面要用数组进行实现    NSArray *fileNames = [fmcontentsOfDirectoryAtPath:patherror:nil];获取数组路径下的所有文件内容:

3.遍历数组,在其中进行判断

for (NSString *fileNamein fileNames) {

              //开始

        if ([fileNamehasSuffix:@"jpg"]||[fileNamehasSuffix:@"png"]) {

Nslog(@"%@",filename);    找到桌面的所有图片并输出   如果要删除的话:【FMREMOVEATPATH FILEPATH ERROR:NIL】;加上这个

下一个需求,将找到的所有图片全都删掉的话:

需要找到桌面图片的完整路径  :

NSString *filePath= [pathstringByAppendingPathComponent:fileName];需要将当前文件夹的路径和图片名拼接到一起。

//判断是否为文件夹:

BOOL isDir = NO;

        if ([fmfileExistsAtPath:filePathisDirectory:&isDir]&&isDir){

            

           [selffindFileInDirecotryPath:filePath];//如果是文件夹,继续查看它下面的内容;

        }

 NSString *toPath = [@"/Users/bmuyu/Desktop/imgs"stringByAppendingPathComponent:fileName]; //将桌面的所有图片移动到这个路径下。

 

[selffindFileInDirecotryPath:@"/Users/"];

}

完整代码的意思是  查找Users路径下所有PNGJPG格式的图片移动到/Users/bmuyu/Desktop/imgs这个路径下 然后做一个计数,需要声明int变量

-(void)findFileInDirecotryPath:(NSString *)path{

    NSFileManager *fm = [NSFileManagerdefaultManager];

    NSArray *fileNames = [fmcontentsOfDirectoryAtPath:patherror:nil];

    

    for (NSString *fileNamein fileNames) {

        NSString *filePath =[pathstringByAppendingPathComponent:fileName];

        //开始

        if ([fileNamehasSuffix:@"jpg"]||[fileNamehasSuffix:@"png"]) {

           self.count++;//图片计数~

            NSLog(@"%d",self.count);

           //准备新的路径仍然是原来的文件名称

            NSString *toPath = [@"/Users/bmuyu/Desktop/imgs"stringByAppendingPathComponent:fileName];

            

            [fm moveItemAtPath:filePathtoPath:toPatherror:nil];

        }

        

        //判断是否是文件夹

        BOOL isDir =NO;

        if ([fmfileExistsAtPath:filePathisDirectory:&isDir]&&isDir){

            

            [selffindFileInDirecotryPath:filePath];

        }

0 0
原创粉丝点击