2014-11-14 64 views
1

我有一个UICollectionView并在每个单元格中加载图像。图像加载由SDWebImage处理,并下载为UICollectionView和图像加载导致内存不足

[_ImageView sd_setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"Icon-120"]]; 

插入到集合视图是由代码

for(NSString *data in datas) 
{ 
    Cell *newCell = [[Cell alloc] initWithDictionary:cellDict]; 
    [_allcells insertObject:newCell atIndex:0]; 
    [_collectionView reloadData];               
} 

当用户触摸它们收集视图开除处理,我清空数据源。

- (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"];  

应该清除所有分配。请帮我解决我做错的事。

+0

尝试使用'[SDImageCache sharedImageCache] clearMemory]'方法清除内存高速缓存 – jamapag 2014-11-14 20:26:13

+0

这并没有帮助。 :( – user1191140 2014-11-14 20:28:08

回答

1

从iOS 7开始NSCache只会在您设置为totalCostLimitcountLimit属性时才会自动删除缓存对象。

SDImageCache尝试使用NSCachetotalCostLimit来限制存储缓存图像的数量。但它从不为共享的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; 

如果不设置SDImageCachemaxMemoryCost只会在内存警告删除MEM缓存图像。

你可以阅读更多有关图像缓存和NSCachehere

相关问题