objective-c - 复制文件而不卡住 GUI

标签 objective-c macos cocoa

好的,基本上这就是我想做的:

  • 我的应用程序包中有一个文件列表,例如在文件夹 myData 中(请注意:子文件夹/等中有很多文件/文件夹)
  • 我想将整个文件树复制到用户磁盘上的给定位置
  • 我需要访问正在复制的每个单独文件,因为其中一些文件需要在复制之前进行处理。

你会怎么做?有什么想法吗?

<小时/>

附注

  • 我了解 NSFileWrapperwriteFile:atomically:updateFilenames,但它并不能让我访问每个文件
  • 我已经有了一种获取特定文件夹的文件树的方法。然而,在我看来,它仍然有点慢。有没有内置的(或更适合 cocoa 的)方法?
  • 由于文件相当多,因此必须运行整个过程,以便 GUI 不会卡住

最佳答案

使用 Grand Central Dispatch(GCD) 在异步线程中运行方法

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 从文件/文件夹的数量指示文件操作的进度。

关于objective-c - 复制文件而不卡住 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18333143/

相关文章:

ios - 如何使 UITextField 文本输入在 5-6 个空格字符后开始

objective-c - 如何在 NSView 的 subview 上绘制

objective-c - 创建仅使用非英语语言的应用程序的正确方法

ios - Swift 协议(protocol)中的可选方法和重载

macos - NSTableView hideRows 在旧行曾经所在的位置留下空白空间

objective-c - 我可以在 superView 的特定点获取 subView 吗?

objective-c - 可以从watchkit观看运行视频吗?

Python - 没有名为 setuptools 的模块

objective-c - 如何在自定义 NSView 中设置光标?

objective-c - 从菜单中删除 'Start Dictation' 和 'Special Characters'