3 回答

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用KVO觀察operations隊(duì)列的屬性,然后通過檢查可以判斷隊(duì)列是否已完成[queue.operations count] == 0。
在您正在執(zhí)行KVO的文件中的某處,像這樣聲明KVO的上下文(更多信息):
static NSString *kQueueOperationsChanged = @"kQueueOperationsChanged";
設(shè)置隊(duì)列時(shí),請(qǐng)執(zhí)行以下操作:
[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];
}
}
(這是假設(shè)您NSOperationQueue位于名為的屬性中queue)
在對(duì)象完全解除分配之前(或當(dāng)它停止關(guān)心隊(duì)列狀態(tài)時(shí)),在某些時(shí)候,您需要像這樣從KVO注銷:
[self.queue removeObserver:self forKeyPath:@"operations" context:&kQueueOperationsChanged];
附錄:iOS 4.0具有一個(gè)NSOperationQueue.operationCount屬性,根據(jù)文檔,該屬性符合KVO。但是,此答案在iOS 4.0中仍然有效,因此對(duì)于向后兼容仍然有用。
- 3 回答
- 0 關(guān)注
- 1453 瀏覽
添加回答
舉報(bào)