关于ios:Ios-多线程之NSOperation与NSOprationQueue

3次阅读

共计 2001 个字符,预计需要花费 6 分钟才能阅读完成。

在说 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];
}

在暗藏和显示复用控件中中断和开启工作。能够在以后控件下解决各种简单工作而不会抵触。例如图片加载,图片压缩,下载回调,异步读取资源等多种状况下都十分实用。

正文完
 0