ios UICollectionView 加载数据后 滑动卡顿问题

最近项目的资源图片变大了,滑动时总是卡顿,在这里用NSOperationQueue解决了一下

.h 文件
@interface CollectionViewCell : UICollectionViewCell
// 赋值
@property (nonatomic, strong) NearRentListModel *listModel;
// 队列
@property (nonatomic, strong) NSOperationQueue *queue;

.m 文件
// 懒加载
- (NSOperationQueue *)queue {
    
    if (!_queue) {
        _queue = ({
            NSOperationQueue *q = [[NSOperationQueue alloc]init];
            //设置最大并行操作数为1相当于将queue设置为串行线程
            q.maxConcurrentOperationCount = 1;
            q;
        });
    }
    return _queue;
}
// 调用set方法
- (void)setListModel:(NearRentListModel *)listModel {
    
    _listModel = listModel;
   // 这里展示其他数据(根据项目需要而定)
      
// 开始使用,解决卡顿
if (self.queue.operationCount >= 2) {
        //如果self.queue.operations[0]正在执行的话,不会被强行中止
        [self.queue cancelAllOperations];
    }
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(loadImg)
                                        object:nil];
    
    [self.queue addOperation:operation];
    
}

// 调用 展示网络图片
- (void)loadImg{
    dispatch_async(dispatch_get_main_queue(), ^{
         [_headerImg sd_setImageWithURL:[NSURL URLWithString:_listModel.avatar_path] placeholderImage:MoTo_User_headerimage];
        
        [_img sd_setImageWithURL:[NSURL URLWithString:_listModel.cover_photo] placeholderImage:nil];
    });
}

猜你喜欢

转载自www.cnblogs.com/xingsmile/p/11145471.html