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

      参考: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以上。

你可能感兴趣的:(iOS)