当 NSOperationQueue 完成所有任务时获取通知 [英] Get notification when NSOperationQueue finishes all tasks
问题描述
NSOperationQueue
有 waitUntilAllOperationsAreFinished
,但我不想同步等待它.我只想在队列完成时隐藏 UI 中的进度指示器.
NSOperationQueue
has waitUntilAllOperationsAreFinished
, but I don't want to wait synchronously for it. I just want to hide progress indicator in UI when queue finishes.
实现这一目标的最佳方法是什么?
What's the best way to accomplish this?
我无法从我的 NSOperation
发送通知,因为我不知道哪个将是最后一个,而且 [队列操作]
可能不会收到通知时为空(或更糟 - 重新填充).
I can't send notifications from my NSOperation
s, because I don't know which one is going to be last, and [queue operations]
might not be empty yet (or worse - repopulated) when notification is received.
推荐答案
使用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.
这篇关于当 NSOperationQueue 完成所有任务时获取通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!