我有一个 UICollectionView 并在每个单元格中加载图像。图片加载由 SDWebImage 处理,下载为
[_ImageView sd_setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"Icon-120"]];
Collection View 的插入由代码处理
for(NSString *data in datas)
{
Cell *newCell = [[Cell alloc] initWithDictionary:cellDict];
[_allcells insertObject:newCell atIndex:0];
[_collectionView reloadData];
}
当用户触摸它们并且我清空数据源时, Collection View 被关闭。
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[_collectionView setHidden:YES];
[_allcells removeAllObjects];
[[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
}
当我在 5/6 次后运行此代码时,我收到内存不足警告。我试图清空图像下载的内存缓存。
- (void)didReceiveMemoryWarning {
// Dispose of any resources that can be recreated.
[[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
[_collectionView setHidden:YES];
[_allcells removeAllObjects];
[super didReceiveMemoryWarning];
NSLog(@"Received Low Memory");
}
我尝试附加仪器并查看分配。每次下载图像时,我都会看到 5 x 8.1 MB CoreImage 分配。我的印象是,当我调用
[[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
所有分配都应该被清除。请帮助我解决我做错的事情。
最佳答案
从 iOS 7 开始,NSCache
将仅在您设置它的 totalCostLimit
或 countLimit
属性时自动删除缓存对象。
SDImageCache
尝试使用 NSCache
totalCostLimit
来限制内存缓存图像的数量。但它从不为共享的 SDImageCache
实例设置 maxMemoryCost
。显然你应该自己做。
这就是他们计算每张图片成本的方式:
[self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale * image.scale];
所以它只是一个图像像素大小。我们假设每个像素在内存中占用 32 位(您可以使用 CGImageGetBitsPerPixel
函数检查每个像素的实际位数,但 SDImageCache
会忽略它)。所以每个像素大概在内存中占用 4 个字节。
尝试将 maxMemoryCost
限制设置为合理的数量。像这样:
NSProcessInfo *info = [NSProcessInfo processInfo];
// Compute total cost limit in bytes
NSUInteger totalCostLimit = (NSUInteger)(info.physicalMemory * 0.15); // Use 15% of available RAM
// Divide totalCostLimit in bytes by number of bytes per pixel
[[SDImageCache sharedImageCache].maxMemoryCost = totalCostLimit / 4;
如果您没有设置 SDImageCache
的 maxMemoryCost
,它只会在出现内存警告时删除内存缓存的图像。
您可以阅读有关图像缓存和 NSCache
的更多信息 here
关于ios - UICollectionview 和 Image loading 导致内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26938085/