大家好,我正在尝试使用NSCache通过URL管理从Firebase拍摄的图像。我使用NSCache是因为每次我浏览带有用户照片的表格视图时,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;
}
答案 0 :(得分:1)
似乎问题在于您正在NSCache
方法中创建loadImageUsingCacheWithURLString:
的新实例。当单元被重用并且未缓存的新图像被获取时,您正在创建一个新的NSCache
,它将仅保留最后一个加载的图像。您是否可以尝试仅在单元格的初始化程序中实例化缓存,看看是否可行?或者,也许考虑使用不是该单元格属性的缓存,以避免将相同的图像加载到2个不同的单元格中。