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

NSOperationQueue具有waitUntilAllOperationsAreFinished,但我不想同步等待它。我只想在队列完成时在UI中隐藏进度指示器。


做到这一点的最佳方法是什么?


我无法从NSOperations 发送通知,因为我不知道哪个将是最后一个,并且[queue operations]在收到通知时可能还不为空(或者更糟-已重新填充)。


芜湖不芜
浏览 1363回答 3
3回答

MMMHUHU

使用KVO观察operations队列的属性,然后通过检查可以判断队列是否已完成[queue.operations count] == 0。在您正在执行KVO的文件中的某处,像这样声明KVO的上下文(更多信息):static NSString *kQueueOperationsChanged = @"kQueueOperationsChanged";设置队列时,请执行以下操作:[self.queue addObserver:self forKeyPath:@"operations" options:0 context:&kQueueOperationsChanged];然后在您的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)在对象完全解除分配之前(或当它停止关心队列状态时),在某些时候,您需要像这样从KVO注销:[self.queue removeObserver:self forKeyPath:@"operations" context:&kQueueOperationsChanged];附录:iOS 4.0具有一个NSOperationQueue.operationCount属性,根据文档,该属性符合KVO。但是,此答案在iOS 4.0中仍然有效,因此对于向后兼容仍然有用。
打开App,查看更多内容
随时随地看视频慕课网APP