Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispatch a block with parameter on main queue or thread

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?

like image 385
epologee Avatar asked Dec 02 '22 01:12

epologee


1 Answers

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?

like image 184
kperryua Avatar answered Dec 04 '22 02:12

kperryua