首页 > 解决方案 > 使用 Firebase 的 NSCache 存储图像 - 目标 C

问题描述

大家好,我正在尝试使用 NSCache 来管理通过 URL 从 Firebase 获取的图像。我使用 NSCache 是因为每次我用用户的照片浏览 tableview 时,imageView 都会不断补偿,所以我想使用 NSCache 来想象图像只加载一次并存储在缓存中......所有这些都不起作用,但每次我浏览表格视图时,我的图像都会不断充电。

有人可以解释我错在哪里吗?非常感谢您能给我的任何答案...

我的项目在 Objective C 中

这是我在自定义单元格中的代码

@interface UserListMessageCell ()
@property (nonatomic, strong) NSURLSessionTask *task;
@property (nonatomic, strong) NSCache *imageCache;
@end

@implementation UserListMessageCell

-(void)loadImageUsingCacheWithURLString:(NSString *)urlString {

    UIImage *cachedImage = [_imageCache objectForKey:urlString];

    if (cachedImage) {
        _userPhoto.image = cachedImage;
        return;
    }


     _imageCache = NSCache.new

     NSURL *url = [NSURL URLWithString:urlString];
    [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:data];

            if (image) {
                self.imageCache = NSCache.new;
                [self.imageCache setObject:image forKey:urlString];
                self.userPhoto.image = image;
            }

            else self.userPhoto.image = [UIImage imageNamed:@"user"];
        });
    }] resume];
}

@end

这是我在 TableView 中的实现

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserListMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];

    UserReference *userRef = _isFiltered ? self.filteredUser[indexPath.row] : self.userArray[indexPath.row];

    cell.userNameLabel.text = userRef.name;
    cell.userUniversityLabel.text = userRef.university;
   [cell loadImageUsingCacheWithURLString:userRef.urlPhoto];

    return cell;
}

标签: objective-cfirebaseuiimageviewuiimagenscache

解决方案


似乎问题是您正在方法中创建一个新NSCache实例loadImageUsingCacheWithURLString:。当重新使用单元格并获取未缓存的新图像时,您正在创建一个新NSCache图像,它将仅保留最后加载的图像。您可以尝试仅在单元的初始化程序中实例化缓存并查看是否有效吗?或者可能考虑使用不是单元属性的缓存,以避免在 2 个不同的单元中加载相同的图像。


推荐阅读