Blocks are awesome. Because I thought I understood them, I wanted to up the ante and use them in a little more complex situation. Now these blocks are kicking me in the face, and I'm trying to break it down into comprehensible pieces.
Say I have two blocks in this pseudo code conveniently named blockA
and blockB
. The first is a simple parameter-less block and it just prints a line. The second takes one parameter xyz
of type id
:
void (^blockA){ NSLog(@"Doing something"); };
void (^blockB)(id xyz){ [xyz doSomething]; };
When running blockA
, I would do something like blockA();
or when I want to target the main queue/thread, I use the dispatch_sync
or _async
method:
dispatch_sync(dispatch_get_main_queue(), blockA);
But although I know how to dispatch blockB
with a parameter like blockB(someObject);
, I can't figure out how to explicitly call that one on the main thread. I was looking for something like the next line, but of course that's not how this works:
dispatch_sync(dispatch_get_main_queue, blockB, someObject);
Now I've tried wrapping the block in another block, but to be honest that just doesn't look right and it felt like it was causing more problems than it solved. Is there something other than wrapping blocks to dispatch one block with one or more parameters on the main queue/thread?
Nope. Wrapping blocks is exactly what you have to do in this case. In code:
void (^block)(id someArg) = someBlock;
id object = someObject;
dispatch_async(dispatch_get_main_queue(), ^{
block(someObject);
});
It may look a little strange at first, but this style makes the dispatch APIs so much simpler and the automatic retaining of captured variables makes it possible. I'm a little surprised you ran into problems. What were they?
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