objective-c - 使用 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;
}
解决方案
似乎问题是您正在方法中创建一个新NSCache
实例loadImageUsingCacheWithURLString:
。当重新使用单元格并获取未缓存的新图像时,您正在创建一个新NSCache
图像,它将仅保留最后加载的图像。您可以尝试仅在单元的初始化程序中实例化缓存并查看是否有效吗?或者可能考虑使用不是单元属性的缓存,以避免在 2 个不同的单元中加载相同的图像。
推荐阅读
- python - 如何从大文件中删除未知的额外数据值?
- ruby-on-rails - 将变量插入到从不同目录声明的 .html.slim 文件中
- javascript - 如何将元素/img 锚定在 div 屏幕的特定部分?
- recursion - F# Console.ReadLine 不等待输入
- spring-boot - 如何停止准备在Kafka中与老年代重新平衡组?
- unity3d - 移动构建中的对象似乎扭曲了
- php - “未定义变量:环境”如何获取 App::enviroment()?
- bootstrap-5 - Bootstrap v5 Grid 在“col-lg”情况下不起作用
- pandas - 使用 Pandas 有条件地删除行和填充值
- node.js - 有没有办法使用 Node-JS 将图像传输到 IoT 边缘设备中的目录?