/** 定义操作缓存属性 */
@property (nonatomic, strong) NSMutableDictionary *operations;
// 操作缓存属性懒加载实现
- (NSMutableDictionary *)operations{
if (!_operations) {
_operations = [NSMutableDictionary dictionary];
}
return _operations;
}
// 设置图标的位置修改如下:
// 先去查看内存缓存中该图片有没有被下载过,如果有直接拿来用,如果没有就去检查磁盘缓存,如果没有磁盘缓存,就保存一份到内存,设置图片,否则就直接下载。
UIImage *image = [self.images objectForKey:item.icon];
// 如果有值直接拿来直接使用
if(image){
cell.imageView.image = image;
NSLog(@"使用了内存缓存中的图片----%zd",indexPath.row);
}else{
// 沙盒缓存路径获取(磁盘缓存)
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 获得图片的名称
NSString *imageName = [item.icon lastPathComponent];
// 拼接全路径
NSString *fullPath = [cachePath stringByAppendingPathComponent:imageName];
// 检查磁盘缓存
NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
if (imageData) {
// 设置图标
UIImage *image = [UIImage imageWithData:imageData];
cell.imageView.image = image;
NSLog(@"沙盒存储----%zd",indexPath.row);
// 保存图片到内存缓存
[self.images setObject:image forKey:item.icon];
}else{
NSBlockOperation *blockOperation = [self.operations objectForKey:item.icon];
if (blockOperation) {
}else{
// 防止cell重用导致的数据错乱 先设置cell 的 image为空
cell.imageView.image = [UIImage imageNamed:@"placeHolder.png"];
// 创建下载操作
blockOperation = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:item.icon];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
NSLog(@"下载------%@",[NSThread currentThread]);
// 当url地址不正确 image为空 容错处理
if (!image) {
// 为了下一次进来的时候再次尝试进行图片下载
[self.operations removeObjectForKey:item.icon];
return ;
}
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
cell.imageView.image = image;
NSLog(@"UI------%@",[NSThread currentThread]);
// 手动刷新 刷新UITableView指定的行
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
}];
// 保存图片到内存缓存 用图片的URL作为图片的key 保证key唯一
[self.images setObject:image forKey:item.icon];
// 保存图片到沙盒缓存(磁盘缓存)
[imageData writeToFile:fullPath atomically:YES];
// 下载操作完成后进行移除操作
[self.operations removeObjectForKey:item.icon];
}];
[self.operations setObject:blockOperation forKey:item.icon];
[self.queue addOperation:blockOperation];
}
}
}