1

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

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

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

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

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

泄漏仪器截图 1

下载 6 MB 图像后泄漏仪器的屏幕截图。

泄漏仪器屏幕截图 2

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

 - (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;
}
4

1 回答 1

1

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

于 2015-04-18T13:09:12.053 回答