复制文件而不冻结GUI [英] Copy Files without freezing GUI

查看:61
本文介绍了复制文件而不冻结GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以基本上这就是我想做的事情:

OK, so basically here's what I want to do :


  • 我的 app捆绑包中有文件列表,例如在文件夹 myData 中(请注意:子文件夹/等中有很多文件/文件夹)

  • 我要复制整个文件树到用户磁盘上的给定位置

  • 我需要对复制的每个单独文件具有访问权限,因为其中有些会在复制之前需要进行处理。

  • I have a list of files in my app bundle, e.g. in folder myData (please note: there are lots of files/folders within subfolders/etc)
  • I want to copy the whole file tree to a given location on user's disk
  • I need to have access to each separate file being copied, since some of them will need to be processed before being copied.

您将如何处理?有什么想法吗?

How would you go about that? Any ideas?

PS


  • 我知道 NSFileWrapper writeFile:atomically:updateFilenames ,但是它没有不好意思访问每个文件

  • 我已经有了一种获取特定文件夹的文件树的方法。但是,在我看来,它仍然有点慢。

  • 由于有很多内置(或更友好的可可方式)文件,由于文件很多,因此必须运行整个过程,以便GUI执行冻结

  • I know about NSFileWrapper's writeFile:atomically:updateFilenames, but it doesn't gie me access to each file
  • I already have a method for getting the file tree for a specific folder. However, it still seems to me kinda slow. Is there any built-in (or more Cocoa-friendly) way for that?
  • Since there are quite a lot of files, the whole process must run so that the GUI does not freeze

推荐答案

使用Grand Central Dispatch(GCD)在以下方法中运行方法

use Grand Central Dispatch(GCD) to run method in asynchronously thread using

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // user disk space - will use user document
    NSString *docuemntPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    // app bundle folder
    NSString *bundleRoot = [[NSBundle mainBundle] resourcePath];
    NSString *folderPath = [bundleRoot stringByAppendingPathComponent:@"aFolder"];

    NSArray *files = [[NSFileManager defaultManager] enumeratorAtPath:folderPath].allObjects;

    for (NSString *aFile in [files objectEnumerator]) { 
        NSString *copyPath = [folderPath stringByAppendingPathComponent:aFile];
        NSString *destPath = [docuemntPath stringByAppendingPathComponent:aFile];

        NSError *error;
        if ([[NSFileManager defaultManager] copyItemAtPath:copyPath toPath:destPath error:&error]) {
            NSLog(@"Copying successful");
            // here add a percent to progress view 
        } else {
            NSLog(@"Copying error: %@", error.userInfo);
        } 
    }

  // When the copying is finished update your UI 
  // on the main thread and do what ever you need with the object 
  dispatch_async(dispatch_get_main_queue(), ^{
    [self someMethod:myData];
  });
});

,并在主线程上使用UIProgressView从文件数/中指示文件操作的进度文件夹。

and on your main thread use a UIProgressView to indicate the progress of file operation from the number of files/folder.

这篇关于复制文件而不冻结GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆