I\'ve got a bunch of NSOperations added to a NSOperationQueue. The operation queue has the maxConcurrentOperationCount set to 1, so th
I came up with another seemingly better way to ensure that an operaion is executed only if certain conditions (based on the results of previously finished operations) are met, else, the operation is cancelled.
One important consideration here is that the condition check for running an operation should not be coded inside the operation subclass, thus allowing the operation subclass to be poratble across different scenarios and apps.
Solution: - Have a condition block property inside the subclass, and set whatever condition form where the operation is instantiated. - Override "isReady" getter of the NSOperation subclass, check the condition there, and thus determine if its ready for execution. - If [super isReady] is YES, which means the dependent operations are all finished, then evaluate the necessary condition. - If the condition check is passed, return YES. Else, set isCancelled to YES and return YES for isReady
Code: In the interface file have the block property:
typedef BOOL(^ConditionBlock)(void);
@property (copy) ConditionBlock conditionBlock;
In the implementation, override isReady, and cancelled:
@implementation ConditionalOperation
- (BOOL)isReady {
if([super isReady]) {
if(self.conditionBlock) {
if(!self.conditionBlock()) {
[self setCancelled:YES];
}
return YES;
} else {
return YES;
}
} else {
return NO;
}
}