我正在使用 NSOperation 的子类来执行一些后台进程。我希望在用户单击按钮时取消操作。
这是我的 NSOperation 子类的样子
- (id)init{
self = [super init];
if(self){
//initialization code goes here
_isFinished = NO;
_isExecuting = NO;
}
return self;
}
- (void)start
{
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
return;
}
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
//operation goes here
}
- (void)finish{
//releasing objects here
[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
_isExecuting = NO;
_isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
- (void)cancel{
[self willChangeValueForKey:@"isCancelled"];
[self didChangeValueForKey:@"isCancelled"];
[self finish];
}
这就是我将此类的对象添加到队列并侦听 KVO 通知的方式
operationQueue = [[NSOperationQueue alloc] init]; [操作队列 setMaxConcurrentOperationCount:5]; [operationQueue addObserver:self forKeyPath:@"operations" options:0 context:&OperationsChangedContext];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &OperationsChangedContext) {
NSLog(@"Queue size: %u", [[operationQueue operations] count]);
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
要取消操作(例如单击按钮),我尝试调用 -cancel 但它没有任何区别。还尝试调用 -finish 但即使这样也不会改变任何东西。
每次我向队列添加操作时,队列大小只会增加。调用完成(使用 NSLog 语句检查),但它并没有真正结束操作。我仍然不太有信心我做对了
有人可以告诉我哪里出错了吗?
非常感谢