第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

Ios 多線程之NSOperation與NSOprationQueue

標(biāo)簽:
iOS

在说NSOperation之前,先说一下gcd,gcd 技术是一个轻量的,底层实现隐藏的神奇技术,我们能够通过gcd和block轻松实现多线程编程,有时候,gcd相比其他系统提供的多线程方法更加有效,当然,有时候gcd不是最佳选择,另一个多线程编程的技术 NSOprationQueue 让我们能够将后台线程以队列方式依序执行,并提供更多操作的入口,这和 gcd 的实现有些类似。

这种类似不是一个巧合,在早期,MacOX 与 iOS 的程序都普遍采用Operation Queue来进行编写后台线程代码,而之后出现的gcd技术大体是依照前者的原则来实现的,而随着gcd的普及,在iOS 4 与 MacOS X 10.6以后,Operation Queue的底层实现都是用gcd来实现的。

所以,目前可以利用Operation Queue上层的封装,比较简易的实现更简单的多线程操作。

在复用控件,或者多任务执行的情况下,避免不了要开启多个线程和中断线程。

此时,我们就可以使用NSOperation来异步执行任务和中断任务。
包括IOS UITableView和UICollectionView中的cell复用状态下的多线程操作


@property (strong, nonatomic) NSOperationQueue *operationQueue;
@property (strong, nonatomic) NSMutableDictionary *operationDict;



- (NSMutableDictionary *)operationDict {
  if (!_operationDict) {
    _operationDict = [NSMutableDictionary dictionary];
  }
  return _operationDict;
}

- (NSOperationQueue *)operationQueue {
  if (!_operationQueue) {
    _operationQueue = [[NSOperationQueue alloc] init];
    _operationQueue.maxConcurrentOperationCount = 6;
  }
  return _operationQueue;
}

//控件显示开启任务
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {

  if (![self.operationDict objectForKey:@(indexPath.item).stringValue]) {
    NSBlockOperation *operation = [self operationEvent:indexPath.item];
    [self.operationQueue addOperation:operation];
    [self.operationDict setObject:operation forKey:@(indexPath.item).stringValue];
  }
}

//控件消失中断任务
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {

  if (self.operationDict[@(indexPath.item).stringValue]) {
    NSBlockOperation *operation = self.operationDict[@(indexPath.item).stringValue];
    [operation cancel];
    [self.operationDict removeObjectForKey:@(indexPath.item).stringValue];
  }
}

//异步任务
- (NSBlockOperation *)operationEvent:(NSInteger)index {
  WEAKSELF
  NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
  
  }];
  return operation;
}

- (void)dealloc
{
  NSLog(@"释放%@",self);
  [self.operationQueue cancelAllOperations];
}

在隐藏和显示复用控件中中断和开启任务。可以在当前控件下处理各种复杂任务而不会冲突。例如图片加载,图片压缩,下载回调,异步读取资源等多种情况下都非常实用。

點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評(píng)論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評(píng)論
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消