I would like to pass in different blocks into a method. The method would subsequently use the passed in block as parameter to dispatch_async.
I have my block declared like this:
typedef int (^ComputationBlock)(int);
The class method that accepts the block is implemented as:
- (void)doSomething:(int)limit withBlock:(ComputationBlock)block;
{
dispatch_queue_t queue = dispatch_get_global_queue开发者_开发百科(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// typical in-lined block for dispatch_async:
dispatch_async(queue, ^{
// do some work here
});
// I want to pass in the block as the 2nd parameter to dispatch_async
// but the compiler will warn me of a type mismatch unless I cast
// the block like:
dispatch_async(queue, (dispatch_block_t)block);
}
@end
Is it okay to typecast the 'block
' parameter as dispatch_block_t
?
No, that's not cool to do -- the block passed to dispatch_async needs to take no parameters and return nothing. Casting your ComputationBlock to that would be a Bad Idea (it's not nice to fool mother nature).
Simply wrap your block that you want to call inside one of the right type:
dispatch_async(queue, ^{ block(0); } );
(note that you also need to supply a parameter to your ComputationBlock when you invoke it.)
It may compile, but it won't work. dispatch_block_t
blocks must not take any arguments and must not have a return value.
Pass value using __block
__block int backValue;
it can modify in block
精彩评论