one of the central tenets of the architecture of my latest app is that I'm going to call methods on the app's model which will be async and accept failure and success scenario blocks.
i.e., The UI calls the model method with 2 blocks, one for success and one for failure.
This is great because the context of the original call is retained, however, the block itself is called on the background thread. Is there anyway of calling a block on the main thread??
Hopefully I have explianed it ok, if not, basically, my model methods are async, return immediately and create a new thread on which to run the op. Once the op returns I will invoke a block which will postprocess the returned data, THEN i need to call the block for the success scenario defined by the called inside the UI. However, the success and failure scenario blocks defined in the UI should be called in the main thread because I need to interact with UI elements which should only be done on the main thread I believe.
many thanks
Something like this is probably what you're after:
- (void) doSomethingWhichTakesAgesWithArg: (id) theArg
resultHandler: (void (^)(BOOL, id, NSError *)) handler
{
// run in the background, on the default priority queue
dispatch_async( dispatch_get_global_queue(0, 0), ^{
id someVar = [theArg computeSomething];
NSError * anError = nil;
[someVar transmuteSomehowUsing: self error: &anError];
// call the result handler block on the main queue (i.e. main thread)
dispatch_async( dispatch_get_main_queue(), ^{
// running synchronously on the main thread now -- call the handler
handler( (error == nil), theArg, anError );
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With