使用SDWebImage加载图片,当列表有很多页,图片很多时,可能会导致内存暴涨:
产生内存暴涨的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key { UIImage *diskImage = [self diskImageForKey:key]; if (diskImage && self.config.shouldCacheImagesInMemory) { NSUInteger cost = SDCacheCostForImage(diskImage); [self.memCache setObject:diskImage forKey:key cost:cost]; }
return diskImage; }
- (nullable UIImage *)diskImageForKey:(nullable NSString *)key { NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; if (data) { UIImage *image = [[SDWebImageCodersManager sharedInstance] decodedImageWithData:data]; image = [self scaledImageForKey:key image:image]; if (self.config.shouldDecompressImages) { image = [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&data options:@{SDWebImageCoderScaleDownLargeImagesKey: @(NO)}]; } return image; } else { return nil; } }
|
关闭缓存图片到内存的功能:
[[SDImageCache sharedImageCache].config setShouldCacheImagesInMemory:NO];
效果如下:
此时虽然内存不再异常,但滑动过程中会明显看到图片填充时的闪动,用户体验想当不好.
比较好的办法:
1 2 3 4 5 6
| - (void)initSDWebImage { [[SDImageCache sharedImageCache].config setShouldDecompressImages:NO]; [[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO]; [[SDImageCache sharedImageCache] setMaxMemoryCost:20 * 1024 * 1024]; }
|
设置一个内存缓存最大值,需要注意的是系统并不会精确的使用该值进行限定.这样设置之后,内存基本在70-90M之间浮动.不会再像之前飙到3-400M还停不下来.
如果设置为10 1024 1024,那么内存基本在30-50M之间.并且用户体验还行.