现在的位置: 首页 > 综合 > 正文

NSOperationQueue线程队列完毕finished状态检测

2018年05月11日 ⁄ 综合 ⁄ 共 2198字 ⁄ 字号 评论关闭

  参考http://stackoverflow.com/questions/1049001/get-notification-when-nsoperationqueue-finishes-all-tasks

     多线程编程中,操作队列NSOperationQueue我们经常会用到的,简化了多线程的操作。至于用法就不多介绍了。这里要说的是队列执行完毕的状态检查。

      我们很多时候需要在队列完成之后再进行操作,而何时队列完成,NSOperationQueue并没有内置的didFinishedSelector来供使用,因此需要自己去检查其状态。

      因为NSOperationQueue兼容 key-value coding (KVC) and key-value observing (KVO)机制,因此我们可以观察NSOperationQueue的属性。NSOperationQueue可供监控观察的属性有:

  • operations - read-only property

  • operationCount - read-only property

  • maxConcurrentOperationCount - readable and writable property

  • suspended - readable and writable property

  • name - readable and writable property

实现如下:

1.初始_parseQueue

  1. - (NSOperationQueue *)parseQueue  
  2. {  
  3.     if (nil == _parseQueue)  
  4.     {  
  5.         _parseQueue = [[NSOperationQueue alloc] init];  
  6.         [_parseQueue setSuspended:YES];  
  7.         //[_parseQueue setMaxConcurrentOperationCount:1];  
  8.         [_parseQueue addObserver:self  
  9.                       forKeyPath:@"operations"  
  10.                          options:0  
  11.                          context:nil];  
  12.     }  
  13.       
  14.     return _parseQueue;  
  15. }  

2.加入operation

  1. NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self  
  2.                                                                        selector:@selector(myTask)   
  3.                                                                          object:nil];  
  4. [self.parseQueue addOperation:operation];  
  5. [operation release];<strong>  
  6. rong>  

3.观察值的改变

  1. //KVO,观察parseQueue是否执行完  
  2. - (void)observeValueForKeyPath:(NSString *)keyPath  
  3.                       ofObject:(id)object   
  4.                         change:(NSDictionary *)change   
  5.                        context:(void *)context  
  6. {  
  7.     if (object == self.parseQueue && [keyPath isEqualToString:@"operations"])  
  8.     {  
  9.         if (0 == self.parseQueue.operations.count)  
  10.         {  
  11.             DLog(@"parse finished");  
  12.             //other operation  
  13.             [_parseQueue setSuspended:YES];  
  14.               
  15.         }  
  16.     }  
  17.     else  
  18.     {  
  19.         [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];  
  20.     }  
  21. }  

选择对NSOperationQueue的operations进行观察,而不选operationCount是因为operationCount需要iOS 4.0以上

【上篇】
【下篇】

抱歉!评论已关闭.