我正在使用 NSURLSessionDownload 任务在 UITableViewCells 中下载图像。每个单元格都包含一个 ImageView 和一些关联的文本。
应用程序必须与网络服务同步,并能够在互联网连接不可用时保留数据。所以我使用核心数据来存储文本信息,图像存储在文件系统中。我必须检索的大多数图像大小都在 10 KB 左右。总共只有大约20张图片。然而,其中一张图片是 6 MB。
这是我的问题:下载 10KB 图像时,应用程序使用的堆分配持久字节约为 8 MB。下载 6 MB 图像后,持久字节激增至大约 100 MB,我收到内存警告,有时应用程序会终止。
我不知道如何解决这个问题。欢迎任何帮助。谢谢。
Leaks Instrument 下载较小尺寸图像时的屏幕截图。
下载 6 MB 图像后 Leaks Instrument 的屏幕截图。
这是我用来填充表格 View 单元格的代码:
- (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 - 使用 NSURLSessionDownloadTask 在 UITableView 中下载图像的堆分配激增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29709520/