我在依赖图中有一些NSOperations:
NSOperation *op1 = ...; NSOperation *op2 = ...; [op2 addDependency:op1];
这是我如何运行它们:
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:op1]; [queue addOperation:op2];
现在我需要取消它们.如何确保取消依赖关系图中的所有NSOperations,并且不会取消其他NSOperations?
我尝试过的:
在NSOperation上调用取消不会取消另一个(据我所知):
[op1 cancel]; // doesn't cancel op2 // -- or -- [op2 cancel]; // doesn't cancel op1
取消队列也会取消不属于op1和op2的依赖关系图的操作(如果队列中有任何此类操作):
[queue cancelAllOperations];
所以我使用自定义方法解决了这个问题,该方法以递归方式查看NSOperation的依赖关系并取消它们.但是,我对这个解决方案不满意,因为我觉得我正在与框架作斗争:
- (void)recursiveCancel:(NSOperation *)op { [op cancel]; for (NSOperation *dep in op.dependencies) { [self recursiveCancel:op]; } }
解决方法
不存在NSOperation自动取消其依赖关系的概念.这是因为多个NSOperations可能依赖于相同的其他NSOperation.依赖关系严格存在以延迟特定NSOperation的执行,直到其所有依赖关系NSOperations完成.
您可以考虑编写NSOperation的子类:
@interface NSOperationOneToOne : NSOperation - (void)addOneToOneDependency:(NSOperation *)operation; - (void)removeOneToOneDependency:(NSOperation *)operation; @end @implementation NSOperationOneToOne { NSMutableArray *oneToOneDependencies; } - (void)addOneToOneDependency:(NSOperation *)operation { [oneToOneDependencies addObject:operation]; [self addDependency:operation]; } - (void)removeOneToOneDependency:(NSOperation *)operation { [oneToOneDependencies removeObject:operation]; [self removeDependency:operation]; } - (void)cancel { [super cancel]; [oneToOneDependencies makeObjectsPerformSelector:@selector(cancel)]; } @end