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;
}