tableViewCell的网络图片加载方法

tableViewCell的网络图片加载重点是主要防止图片的重复下载:

情况:

1.打开应用程序,展示tableView的界面时,程序通过网络下载图片,我们滑屏换到下边的cell再回来时防止重新下载

2.图片下载我们用子线程下载,如果图片比较大,在下载过程中,我们滑屏到下边的cell上了,再回来时防止重新开新的线程再下载

解决方法:

创建一全局字典属性

@interface ViewController ()

@property (nonatomic, strong) NSMutableDictionary *imagesDict;
@property (nonatomic, strong) NSMutableDictionary *operationsDict;
@property (nonatomic, strong) NSOperationQueue *queue;

@end
懒加载

//------------------
- (NSMutableDictionary *)imagesDict {
	if (!_imagesDict) {
		_imagesDict = [NSMutableDictionary dictionary];
	}
	return _imagesDict;
}
- (NSMutableDictionary *)operations {
	if (!_operationsDict) {
		_operationsDict = [NSMutableDictionary dictionary];
	}
	return _operationsDict;
}
- (NSOperationQueue *)queue {
	if (!_queue) {
		_queue = [[NSOperationQueue alloc] init];
	}
	return _queue;
}
//------------------

tableViewCell的实现

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	static NSString *identifier = @"imagecellidentifier";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
	if (!cell) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
	}
	
        
	NSString *imageName = @"http://xxxx/image.jpg";
	
	UIImage *image = self.imagesDict[imageName];
	if (!image) {					//image字典中没有图片
		NSOperation *operation = self.operationsDict[imageName];
		if (!operation) {			//queue中没有下载任务
			operation = [NSBlockOperation blockOperationWithBlock:^{
				NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageName]];
				UIImage *imageb = [UIImage imageWithData:imageData];
				
				self.imagesDict[imageName] = imageb;
				self.operationsDict[imageName] = nil;
				
				//主线程中刷新image
				dispatch_async(dispatch_get_main_queue(), ^{
					cell.imageView.image = imageb;
				});
			}];
			[self.queue addOperation:operation];
			self.operationsDict[imageName] = operation;
		} else {					//正在下载
			cell.imageView.image = [UIImage imageNamed:@"dufault.jpg"];
		}
	} else {
		cell.imageView.image = image;
	}
	return cell;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值