【发布时间】: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