ios 不同路径加载 相同图片_iOS图片加载策略的简单实现

/** 定义操作缓存属性 */

@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];

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值