对于tableview加载大量图片时,如果不做优化,就会损耗服务器对app的性能也不好,在面试过程中面试官也比较关心这个问题,进行百度一下有以下思路:
1.在tableview正在快速滚动和缓慢滚动时,如果该图片还没有被加载,那么就要给它一个默认图,否则才进行下载图片。
注:
sdwebimage对下载的图片有缓存作用,downImageArray用于存储那些图片已经下载过的NSIndxPath,tableView属性isDragging表示正在快速滚动,isDecelerating表示正在慢速滚动,当tableView 正在滚动而且该cell 的图片还没下载的时候直接显示占位图片,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@“cell” forIndexPath:indexPath];
if ((self.tableView.isDragging || self.tableView.isDecelerating) && ![self.downImageArray containsObject:indexPath]) {
cell.iconView.image = [UIImage imageNamed:@“1.jpg”];
return cell;
}
[cell.iconView sd_setImageWithURL:[NSURL URLWithString:_array[indexPath.row]] placeholderImage:[UIImage imageNamed:@“1.jpg”] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (![self.downImageArray containsObject:indexPath]) {
[self.downImageArray addObject:indexPath];
}
}];
return cell;
}
//结束快速滚动,开始慢速滚动 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (!decelerate) {
[self reload];
}
}
//慢速滚动结束
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self reload];
}
// 数据刷新 - (void)reload {
NSArray *arr = [self.tableView indexPathsForVisibleRows];
//存储需要下载图片的indexpath
NSMutableArray *arrToReload = [NSMutableArray array];
for (NSIndexPath *indexPath in arr) {
//判断该cell的图片是否已经下载
if (![self.downImageArray containsObject:indexPath]) {
[arrToReload addObject:indexPath];
}
}
[self.tableView reloadRowsAtIndexPaths:arrToReload withRowAnimation:UITableViewRowAnimationNone];
}
//当cell移除界面的时候停止当前正在下载图片 - (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *tableViewCell = (TableViewCell *)cell;
[tableViewCell.iconView sd_cancelCurrentImageLoad];
}
2.苹果官方文档也有介绍该内容LazyTableImages
(本文有参考:https://www.jianshu.com/p/9e503a81de07)