Reputation: 8448
I have an object (Processor
) containing several methods that perform lengthy calculations. I'd like to use those methods both on the main thread and in NSOperation
subclasses.
Inside my NSOperation
subclass code I repeatedly call isCancelled
, so cancellation is fairly responsive. However, when the operation calls one of those lengthy Processor
methods, it isn't able to respond to cancellation until that method returns.
Is there a good way to write methods so they can be used both with and without operations? I'm considering adding an operation
argument to my CPU-intensive Processor
methods and writing them like this:
- (void)calculateWithOperation:(NSOperation *)operation {
do {
if (operation != nil && [operation isCancelled]) {
return;
}
// Do some more calculation...
} while (! finished);
}
// For convenient main thread execution.
- (void)calculate {
[self calculateWithOperation:nil];
}
Has anyone else run into this issue before? Is there a better way?
Upvotes: 2
Views: 238
Reputation: 23722
The only way for an NSOperation to respond to canceling is to check if it's isCancelled as frequently as feasible. After all, it's just a thread which needs to exit when a flag is set. Basically, the isCancelled infrastructure is needed to gracefully free the operation's resources. So I'd say you just have to pepper the expensive method with checks.
Upvotes: 2