UIImageView+AFNetworking 管理缓存和分配

UIImageView+AFNetworking Managing Caching & Allocations

我正在使用 UIImageView+AFNetworking 从 URL 下载并在 UITableView 中显示图像。一切都运行良好,我的问题是围绕通过此调用实现的缓存元素和分配。

在使用仪器跟踪内存时,我看到当我滚动时,我最大的内存分配很快变成了这个 VM: Foundation,它看起来好像正在以某种方式缓存我正在下载的图像。

当用户查看相同的图像但我从未看到它释放内存时,这对用户来说非常有用。 (我还没能把它变成内存警告)。我只是想确保在需要的时候这个分配会在需要的时候被释放。下面是那些 VM : Foundation

的堆栈轨迹

是否需要我监控这个并在需要时释放缓存的内存以确保平滑滚动?或者还有什么我应该注意以确保正确处理的吗?

以下是我调用 cellForRowAtIndexPath 中的图像的方式 我调用 setImageWithURLRequest。任何建议或改进将不胜感激。

   NSString *imageURL = [NSString stringWithFormat:@"https://IMAGE-URL/%@",imageURL];
        __weak MainTableViewCell *weakCell = cell;
        NSURLRequest *urlRequest = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:imageURL]];

        [cell.postImage setImageWithURLRequest:urlRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

            MainTableViewCell *strongCell = weakCell;
            strongCell.postImage.image = image;

            [UIView animateWithDuration:.15 animations:^{
                strongCell.postImage.alpha = 1;
            }];

        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {

        }];

您真的不必担心清除图像缓存,因为 AFNetworking 会自动为您处理。

它将内部图像存储在 NSCache 中,正如 docs 所说:

incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimizing its memory footprint.

但是,在 AFNetworking 开发过程中,在收到 UIApplicationDidReceiveMemoryWarningNotification 时添加了一些 troubles with this automatic removal behaviour, so finally manual cache clearing。但这一切都发生在内部,你不应该自己做。