Monday, May 6, 2013

NSBlockOperation blockOperationWithBlock example ios


Creates and returns an NSBlockOperation object and adds the specified block to it.
+ (id)blockOperationWithBlock:(void (^)(void))block
The block to add to the new block operation object’s list. The block should take no parameters and have no return value.
Return Value of [NSBlockOperation blockOperationWithBlock]
A new block operation object.
Example of [NSBlockOperation blockOperationWithBlock]
- (NSOperation *)executeBlock:(void (^)(void))block inQueue:(NSOperationQueue *)queue completion:(void (^)(BOOL finished))completion {

    NSOperation *blockOperation = [NSBlockOperation blockOperationWithBlock :block];
    NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
    [completionOperation addDependency:blockOperation];

    [[NSOperationQueue currentQueue] addOperation:completionOperation];
    [queue addOperation:blockOperation];
    return blockOperation;

- (void)testIt {

    backgroundOperationQueue = [[NSOperationQueue alloc] init];

    NSMutableString *string = [NSMutableString stringWithString:@"tea"];
    NSString *otherString = @"for";

    NSOperation *operation = [self executeBlock:^{
        NSString *yetAnother = @"two";
        [string appendFormat:@" %@ %@", otherString, yetAnother];
    } completion:^(BOOL finished) {
        // this logs "tea for two"
        NSLog(@"%@", string);

    NSLog(@"keep this operation so we can cancel it: %@", operation);
Example of [NSBlockOperation blockOperationWithBlock]
_requestA = [NSBlockOperation blockOperationWithBlock:^{
    // Normal requestA code here.
    // ...

    // Assuming you create all requestA and requestB instances on the main thread...
    dispatch_async(dispatch_get_main_queue(), ^{ _requestA = nil; });