【发布时间】:2016-04-05 20:13:27
【问题描述】:
我正在使用 AFNetworking 3.0 的 UIImageView+AFNetworking 在 UICollectionView 中显示图像。
但是,随着我不断滚动,我的应用程序的内存使用量不断增长。我使用了 Instruments Allocations 工具,并且能够将问题缩小到 CG 栅格数据,该数据随着加载的每个图像而不断增长。查看CG Raster Data 的详细信息,负责调用者为cgdataprovidercreatewithcopyofdata,负责库为CoreGraphics。对于每个加载的单元格,都会浪费 240 KB 的内存。
堆栈溢出有很多类似的问题,但没有一个真正有帮助/有解决方案。
我认为这可能是由于缓存的原因,所以我启用了以下功能,但完全没有帮助:
NSURLCache * sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:10 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
我尝试将 setImageWithURLRequest 包装在 autoreleasepool 中,但没有帮助。
我尝试在整个应用程序中搜索 cgdataprovidercreatewithcopyofdata,但在我的应用程序或 afnetworking 中没有找到任何匹配项。但是,如果我删除图像的加载,则看不到此问题。
此外,如果我删除完成处理程序中的图像设置,内存仍然会增长。这意味着setImageWithURLRequest 本身是罪魁祸首,而不是完成处理程序中图像的设置。
我已经为此苦苦挣扎了一段时间,任何帮助将不胜感激!
这是我设置图像的代码:
[cell.thumbnail cancelImageDownloadTask];
__weak UIImageView *weakImageView = cell.thumbnail;
@autoreleasepool {
[cell.thumbnail setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myurl/image.png"]]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
UIImageView *strongImageView = weakImageView; // make local strong reference to protect against race conditions
if (!strongImageView) return;
[UIView transitionWithView:strongImageView
duration:0.3
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
strongImageView.image = image;
}
completion:NULL];
}
failure:NULL];
以下是仪器截图:
【问题讨论】:
-
您可以使用 SDWebImage 库来解决泄漏问题,缓存和缓存清除以及其他一些功能也维护在这个库中。这可能会帮助你。 github.com/rs/SDWebImage
-
@AjayGabani 谢谢,我最终使用了它,但它有同样的问题。但是我随后添加了一个每隔几秒钟执行一次以清除缓存的方法,因为 SDWebImage 至少为它提供了一个方法。它似乎大大降低了使用量,不是完全降低了,而是好多了。
标签: ios objective-c memory-leaks uiimageview afnetworking-3