我正在为我的 NSOperationQueue 注册回调,如下所示:
[self.queue addObserver:self forKeyPath:@"operationCount" options:NSKeyValueObservingOptionNew context:NULL];
因为我有一个用于长任务的过期处理程序,所以我在 operationCount 的回调中执行此操作。我基本上是在队列中的 NSOperation 完成后尝试保存状态,然后稍后恢复。所以我这样做:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"operationCount"]) {
NSNumber *num = [change objectForKey:NSKeyValueChangeNewKey];
self.progress = (1.0 - (double)[num integerValue] / self.totalPackets);
if ([UIApplication sharedApplication].backgroundTimeRemaining <= MIN_BACKGROUND_TIME) {
// Background time is almost up, save the state and resume later
NSLog(@"running out of time");
[self.queue cancelAllOperations];
[self.queue removeObserver:self forKeyPath:@"operationCount" context:NULL];
if (self.patientProcessingTaskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.patientProcessingTaskID];
self.patientProcessingTaskID = UIBackgroundTaskInvalid;
}
}
if (self.queue.operationCount == 0) {
NSLog(@"no more operations");
[self.queue removeObserver:self forKeyPath:@"operationCount" context:NULL];
if (self.patientProcessingTaskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.patientProcessingTaskID];
self.patientProcessingTaskID = UIBackgroundTaskInvalid;
}
}
}
}
它不像我预期的那样工作。我单步执行代码,我看到 [self.queue removeObserver:..] 开始运行。但是,我仍然最终在我的 obserValueForKeyPath: 方法中得到一个回调,我不确定为什么(假设我将自己作为 self.queue 的观察者删除了。我是否正确删除了 self?谢谢!