最近項目的資源圖片變大了,滑動時總是卡頓,在這里用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]; }); }