【问题标题】:Store Image with NSCache from Firebase - Objective C使用 Firebase 的 NSCache 存储图像 - 目标 C
【发布时间】:2019-03-31 09:45:42
【问题描述】:

大家好,我正在尝试使用 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-c firebase uiimageview uiimage nscache


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多