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

本文探讨在iOS多线程编程中,如何利用NSOperationQueue简化操作,并着重讲解如何检测队列执行完毕的状态。由于NSOperationQueue没有内置的完成状态通知,开发者可以借助KVO机制,观察其属性变化,如`operationCount`,来判断队列是否已完成所有任务。

摘要生成于 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

- (NSOperationQueue *)parseQueue
{
    if (nil == _parseQueue)
    {
        _parseQueue = [[NSOperationQueue alloc] init];
        [_parseQueue setSuspended:YES];
        //[_parseQueue setMaxConcurrentOperationCount:1];
        [_parseQueue addObserver:self
                      forKeyPath:@"operations"
                         options:0
                         context:nil];
    }
    
    return _parseQueue;
}

2.加入operation

    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                           selector:@selector(myTask) 
                                                                             object:nil];
    [self.parseQueue addOperation:operation];
    [operation release];

3.观察值的改变

//KVO,观察parseQueue是否执行完
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object 
                        change:(NSDictionary *)change 
                       context:(void *)context
{
    if (object == self.parseQueue && [keyPath isEqualToString:@"operations"])
    {
        if (0 == self.parseQueue.operations.count)
        {
            DLog(@"parse finished");
            //other operation
            [_parseQueue setSuspended:YES];
            
        }
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值