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

本文介绍如何在 iOS 多线程编程中利用 NSOperationQueue 的 key-value observing (KVO) 来检测队列任务完成的状态。通过观察 operations 属性,可以在所有任务完成后执行后续操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  参考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以上
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值