3 回答

TA貢獻1834條經驗 獲得超8個贊
使用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中仍然有效,因此對于向后兼容仍然有用。
- 3 回答
- 0 關注
- 1468 瀏覽
添加回答
舉報