ZipArchive阻塞主线程

时间:2014-05-22 14:52:28

标签: ios objective-c zip

当使用ZipArchive解压缩包时,它似乎阻塞了主线程。在zip文件中有大约283个文件。我把它扔在后台线程上,但它似乎并没有帮助。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, (unsigned long) NULL), ^{
    [self tryUnzipFile:fileName inContentPackage:contentPackage];
  });

- (void)tryUnzipFile:(NSString*)fileName inContentPackage:(MKContentPackage*)contentPackage {

  @synchronized (self) {
    NSString *filePath = [contentPackage zipFilePathForFile:fileName];
      BOOL unzipSucceeded = [self unzipFile:filePath toFolder:contentPackage.unzipFolder];
      if (unzipSucceeded) {
        [self excludeFromBackup:contentPackage.downloadFolder];
        NSLog(@"Content: Unzipping Content Package: %@ FileName: %@", contentPackage.identifier, fileName);
      }   
  }
}

- (BOOL)unzipFile:(NSString*)zipFilePath toFolder:(NSString*)zipFolder {
  ZipArchive *zipArchive = [[ZipArchive alloc] init];
  NSString* unzipPath = [NSObject documentFolderFrom:zipFolder fileName:@""];

  // Do the unzipping
  [zipArchive UnzipOpenFile:zipFilePath];
  BOOL unzipped = [zipArchive UnzipFileTo:unzipPath overWrite:YES];
  [zipArchive UnzipCloseFile];

  if (unzipped) {
    [self removeZipPackage:zipFilePath];
  }
  return unzipped;
}

上面这段代码在解压缩时会冻结屏幕大约5秒钟。我假设把它扔在后台线程上会有所帮助,但事实并非如此。任何帮助都是极好的!

1 个答案:

答案 0 :(得分:1)

 @synchronized (self) {
    NSString *filePath = [contentPackage zipFilePathForFile:fileName];
      BOOL unzipSucceeded = [self unzipFile:filePath toFolder:contentPackage.unzipFolder];
      if (unzipSucceeded) {
        [self excludeFromBackup:contentPackage.downloadFolder];
        NSLog(@"Content: Unzipping Content Package: %@ FileName: %@", contentPackage.identifier, fileName);
      }   
  }

如果" self"在此上下文中是View / ViewController,您应该考虑在synchronized块中使用另一个变量。