Skip to content

Instantly share code, notes, and snippets.

@drance
Created August 23, 2013 08:55
Show Gist options
  • Save drance/6317041 to your computer and use it in GitHub Desktop.
Save drance/6317041 to your computer and use it in GitHub Desktop.
This NSOperationQueue category method lets you use a "cancelable" block with NSOperation. By passing the containing operation to the block, the block can return early or respond in other ways if the operation's state changes. The vanilla -addOperationWithBlock: has no reference to the operation, so it's impossible to know, let alone leverage, it…
// Passes the new operation to block so it can check for cancellation and exit early
- (NSOperation *)bhs_addOperationWithCancelableBlock:(void (^)(NSOperation *))block {
NSBlockOperation *op = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOp = op;
[op addExecutionBlock:^{
block(weakOp);
}];
[self addOperation:op];
return op;
}
------------------------
[myQueue bhs_addOperationWithCancelableBlock:^(NSOperation *op) {
if ([op isCancelled]) return;
// Do some work
if ([op isCancelled]) return;
// Rinse, repeat as needed
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment