且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当 NSOperationQueue 完成所有任务时获取通知

更新时间:2023-11-20 23:32:16

使用KVO观察你的队列的operations属性,然后你可以通过检查来判断你的队列是否已经完成[queue.operations count] == 0.

Use KVO to observe the operations property of your queue, then you can tell if your queue has completed by checking for [queue.operations count] == 0.

在您执行 KVO 的文件中的某处,像这样声明 KVO 的上下文 (更多信息):

Somewhere in the file you're doing the KVO in, declare a context for KVO like this (more info):

static NSString *kQueueOperationsChanged = @"kQueueOperationsChanged";

设置队列时,请执行以下操作:

When you setup your queue, do this:

[self.queue addObserver:self forKeyPath:@"operations" options:0 context:&kQueueOperationsChanged];

然后在您的 observeValueForKeyPath 中执行此操作:

Then do this in your observeValueForKeyPath:

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
                         change:(NSDictionary *)change context:(void *)context
{
    if (object == self.queue && [keyPath isEqualToString:@"operations"] && context == &kQueueOperationsChanged) {
        if ([self.queue.operations count] == 0) {
            // Do something here when your queue has completed
            NSLog(@"queue has completed");
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object 
                               change:change context:context];
    }
}

(假设您的 NSOperationQueue 位于名为 queue 的属性中)

(This is assuming that your NSOperationQueue is in a property named queue)

在你的对象完全释放之前的某个时刻(或者当它停止关心队列状态时),你需要像这样从 KVO 注销:

At some point before your object fully deallocs (or when it stops caring about the queue state), you'll need to unregister from KVO like this:

[self.queue removeObserver:self forKeyPath:@"operations" context:&kQueueOperationsChanged];


附录:iOS 4.0 有一个 NSOperationQueue.operationCount 属性,根据文档,它是 KVO 兼容的.但是,此答案在 iOS 4.0 中仍然有效,因此它对于向后兼容性仍然很有用.

Addendum: iOS 4.0 has an NSOperationQueue.operationCount property, which according to the docs is KVO compliant. This answer will still work in iOS 4.0 however, so it's still useful for backwards compatibility.