【问题标题】:Heap allocations spike using NSURLSessionDownloadTask to download images in UITableView堆分配使用 NSURLSessionDownloadTask 来下载 UITableView 中的图像
【发布时间】:2015-04-17 21:19:36
【问题描述】:

我正在使用 NSURLSessionDownload 任务来下载 UITableViewCells 中的图像。每个单元格包含一个图像视图和一些相关的文本。

应用必须与网络服务同步,并且能够在互联网连接不可用时保留数据。所以我使用 Core Data 来存储文本信息,图像存储在文件系统中。我必须检索的大多数图像大小约为 10 KB。总共只有大约 20 张图像。但是,其中一张图片是 6 MB。

这是我的问题:下载 10KB 图像时,应用程序使用的堆分配的持久字节约为 8 MB。下载 6 MB 的图像后,持久字节会飙升至 100 MB 左右,我收到内存警告,有时应用程序会终止。

我不确定如何解决这个问题。欢迎任何帮助。谢谢。

下载较小尺寸图像时泄漏仪器的屏幕截图。

下载 6 MB 图像后的 Leaks Instrument 屏幕截图。

这是我用来填充表格视图单元格的代码:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

  Person *person = [self.fetchedResultsController objectAtIndexPath:indexPath];
  cell.textLabel.text = person.alias;
  cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
  cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", person.status];

  // Determine the path to use to store the file
  NSString *imagePath = [[SyncEngine sharedEngine].imagesDirectory.path stringByAppendingFormat:@"/%@", person.alias];

  if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
    cell.imageView.image = [UIImage imageWithContentsOfFile:imagePath];
  } else {
    cell.imageView.image = [UIImage imageNamed:@"image-placeholder"];
    NSURL *imageURL = [NSURL URLWithString:person.imageURL];
    NSURLSessionDownloadTask *imageDownloadTask = [[SyncEngine sharedEngine].session downloadTaskWithURL:imageURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

  @autoreleasepool {
    NSData *imageData = [NSData dataWithContentsOfURL:location];
    NSLog(@"%@ original image size: %lu B", person.alias, (unsigned long)imageData.length);
    UIImage *image = [UIImage imageWithData:imageData];
    imageData = UIImageJPEGRepresentation(image, 0.2);
    NSLog(@"Compressed: %lu", (unsigned long)imageData.length);

    // Save the image to file system
    NSError *saveError = nil;
    BOOL saved = [imageData writeToFile:imagePath options:0 error:&saveError];
    if (saved) {
      NSLog(@"File saved");
    } else {
      NSLog(@"File not saved:\n%@, %@", saveError, saveError.userInfo);
    }

    dispatch_async(dispatch_get_main_queue(), ^{
      cell.imageView.image = [UIImage imageWithContentsOfFile:imagePath];
    });
  }
}];

    [imageDownloadTask resume];
  }
  return cell;
}

【问题讨论】:

    标签: ios uitableview instruments heap-memory nsurlsessiondownloadtask


    【解决方案1】:

    问题解决了。只需要压缩和调整图像大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多