Created
August 23, 2013 08:55
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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