Skip to content

Instantly share code, notes, and snippets.

@raulraja
Created August 27, 2011 23:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raulraja/1176022 to your computer and use it in GitHub Desktop.
Save raulraja/1176022 to your computer and use it in GitHub Desktop.
Async Operations with ObjectiveC Blocks
/*
* Copyright (C) 2011 47 Degrees, LLC
* http://47deg.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Invokes a block asynchronously and notifies other block handlers of any results or exceptions
* @param asyncBlock the block to be invoked asynchronously
* @param resultBlock the block that would receive the callback if there are no exceptions
* @param errorBlock the block that would receive any exceptions resulting from invoking the asyncBlock
*/
- (void)invokeAsync:(id (^)(void))asyncBlock resultBlock:(void (^)(id))resultBlock errorBlock:(void (^)(id))errorBlock {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id result = nil;
id error = nil;
@try {
result = asyncBlock();
} @catch (NSException *exception) {
NSLog(@"caught exception: %@", exception);
error = exception;
}
// tell the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSAutoreleasePool *secondaryPool = [[NSAutoreleasePool alloc] init];
if (error != nil) {
errorBlock(error);
} else {
resultBlock(result);
}
[secondaryPool release];
});
[pool release];
});
}
//invoke it this way anywhere in your code directly or through a wrapper that delegates the blocks like in this example
/**
* This is a sync operation
*/
- (id)doSomethingSync:(NSString *)param {
//do some work and return something
return nil;
}
/**
* This is an async operation delegating blocks that invokes the above operation
*/
- (void)doSomethingAsync:(NSString *)param onResult:(void (^)(id))resultBlock onError:(void (^)(id))errorBlock {
[self invokeAsync:^{
return [self doSomethingSync:param];
} resultBlock:resultBlock errorBlock:errorBlock];
}
/**
* This is how you invoke the async operation
*/
[someClass doSomethingAsync:@"param value" onResult:^(id result) {
// do something with result
} onError:^(id error) {
//handle any exceptions
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment