我正在研究一个 NSOperation 子类,我遇到了这个非常奇怪的问题,即完成块被连续调用两次。KVO 调用看起来不错,但完成块仍然奇怪地被调用了两次。我误解了 NSOperation 吗?文档说完成块在isFinished
成为时被调用,YES
并且在我的代码中只发生一次:
- (void)main {
@autoreleasepool {
[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isReady"];
executing = YES;
[self didChangeValueForKey:@"isReady"];
[self didChangeValueForKey:@"isExecuting"];
//start the operation
}
}
然后我简单地设置completionBlock
如下:
self.completionBlock = ^{
NSLog(@"Completed");
}
当它完成时,这个方法被调用(它只被调用一次,我仔细检查过)
- (void)completeOperation {
[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
executing = NO;
completed = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
但是,completionBlock 被调用了两次,并在控制台中打印了两次“Completed”。
以下是指示当前状态的方法:
- (BOOL)isReady {
if (executing || cancelled || completed) {
return NO;
}
return YES;
}
- (BOOL)isCancelled {
return cancelled;
}
- (BOOL)isConcurrent {
return YES;
}
- (BOOL)isExecuting {
return executing;
}
- (BOOL)isFinished {
return completed;
}
isCancelled
从来没有YES
在我的测试代码中出现过,所以这不是它的原因。
我真的不明白为什么会调用 completionBlock 两次。即使从完成块内部将完成块设置为零,它有时也会被调用两次,这甚至更奇怪。