iOS tableview滑动优化,SDWebImage+Runloop,图片延迟加载,滑动不加载图片

今天讲讲TableView性能优化之 图片延迟加载, 让滑动更加流畅,而且为了更高效的优化, 每次只处理一屏的图片

Demo地址: https://github.com/MrPlusZhao/TableViewImageCellDemo.git

用Runloop的NSDefaultRunLoopMode 让tableview 在非滑动模式下执行处理图片

 [self performSelector:@selector(p_loadImgeWithIndexPath:) withObject:indexPath afterDelay:0.1 inModes:@[NSDefaultRunLoopMode]];

每次滑动停止 只处理一屏的cell

NSArray *visibleCells = [self.tableView visibleCells];

利用SDWebimage 处理图片相关逻辑

UIImage *originalImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:model.avatar_large];
            if (originalImage) {
                model.cell_Image = originalImage;
                cell.imageV.image = originalImage;
            }
            else{
                [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.avatar_large] placeholderImage:[UIImage imageNamed:@"smallIcon"]];
            }

核心代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DemoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DemoCell"];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"DemoCell" owner:self options:nil].lastObject;
    }
    DemoModel *model = self.dataArr[indexPath.row];
    
    cell.contentLab.text = model.text;
    if (model.cell_Image) {
        cell.imageV.image = model.cell_Image;
    }else{
        cell.imageV.image = [UIImage imageNamed:@"smallIcon"];
    }
    
    [self performSelector:@selector(p_loadImgeWithIndexPath:) withObject:indexPath afterDelay:0.1 inModes:@[NSDefaultRunLoopMode]];
    
    return cell;
}
- (void)p_loadImgeWithIndexPath:(NSIndexPath *)indexPath{
    if ( scrollToToping ) {
        return;
    }
    DemoModel *model = self.dataArr[indexPath.row];
    dispatch_async(dispatch_get_main_queue(), ^{
        DemoCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        NSArray *visibleCells = [self.tableView visibleCells];// 为了优化性能,每次只配置一屏的cell
        if ([visibleCells containsObject:cell]) {
            // 这里下载图片的方式 有很多种, 为了配合当前项目, 目前使用了SDWebimage的方法
            // 方法的目的是一样的, 无图片就去下载, 下载完就赋值给model
            UIImage *originalImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:model.avatar_large];
            if (originalImage) {
                model.cell_Image = originalImage;
                cell.imageV.image = originalImage;
            }
            else{
                [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.avatar_large] placeholderImage:[UIImage imageNamed:@"smallIcon"]];
            }
        }
    });
}

你可能感兴趣的:(iOS tableview滑动优化,SDWebImage+Runloop,图片延迟加载,滑动不加载图片)