iOS文件的剪切

步骤:

  • 1.获取需要剪切文件(夹)的路径from,和要剪切到哪里的路径to
  • 2.获取文件管理者对象(单例)
  • 3.利用文件管理者对象获取数组
  • 4.遍历数组,拼接文件,利用文件管理者剪切文件

方法一:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    NSString *from = @"/Users/chuanzhang/Desktop/from";
    NSString *to = @"/Users/chuanzhang/Desktop/to";

    // 单例对象
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *subPathA = [manager subpathsAtPath:from]; // 文件夹内所有的文件名称
    NSLog(@"%@",subPathA);

    for (int i = 0; i<subPathA.count; i++) {
        // 拼接路径
        NSString *fileName = subPathA[i];
        NSString *fullPath = [from stringByAppendingPathComponent:fileName]; // 这个方法会自动加斜杠

        NSString *toPath = [to stringByAppendingPathComponent:fileName];
        NSLog(@"%@",toPath);

        [manager moveItemAtPath:fullPath toPath:toPath error:nil];
    }

}

方法二:文件剪切属于耗时操作,应该放在子线程中进行

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    NSString *from = @"/Users/chuanzhang/Desktop/from";
    NSString *to = @"/Users/chuanzhang/Desktop/to";

    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *subPathA = [manager subpathsAtPath:from]; // 文件夹内所有的文件名称
   // NSLog(@"%@",subPathA);
    NSInteger count = [subPathA count];

   // dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

  //  GCD迭代,遍历数组
   dispatch_queue_t queue = dispatch_queue_create("com.chuanzhang", DISPATCH_QUEUE_CONCURRENT);
        dispatch_apply(count, queue, ^(size_t i) {

            // 拼接路径
            NSString *fileName = subPathA[i];
            NSString *fullPath = [from stringByAppendingPathComponent:fileName]; // 这个方法会自动加斜杠

            NSString *toPath = [to stringByAppendingPathComponent:fileName];
           // NSLog(@"%@",toPath);
            [manager moveItemAtPath:fullPath toPath:toPath error:nil];

            NSLog(@"%@--",[NSThread currentThread]);
        });
}
文件剪切.png
  • 注意:如图,GCD迭代会开启子线程,但是也会在主线程中执行
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666阅读 1,419评论 0 6
  • 《ilua》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 1...
    叶染柒丶阅读 10,913评论 0 11
  • 1.请简单说明多线程技术的优点和缺点? 优点:能够适当提高程序的执行效率;能够适当的提高资源的利用率,比如CPU、...
    deeper_iOS阅读 1,462评论 1 12
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,201评论 30 471
  • 劝谏是一门艺术。用得恰当可利国利民,拯救万民于水火之中;用得不好,会招来杀身之祸。中国历史上有不少能说会道的...
    2dbd67f8c77a阅读 742评论 0 0