Passing blocks for methods

I would like to pass various blocks to a method. The method will subsequently use the parameter passed to the block for dispatch_async.

I declare my block as follows:

typedef int (^ComputationBlock)(int);

A class method that takes a 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 possible to come up with a ' blockhow dispatch_block_t?

+3
source share
3 answers

No, this is not great to do - the block passed to dispatch_async should not accept any parameters and return nothing. Throwing your ComputationBlock at it would be a bad idea (it’s not good to deceive the nature of the mother).

Just wrap your block that you want to call inside one of the correct types:

 dispatch_async(queue, ^{ block(0); } );    

( , ComputationBlock .)

+12

, . dispatch_block_t .

+4

Skip value with __block

__ block int backValue;

he can change in the block

0
source

Source: https://habr.com/ru/post/1783979/


All Articles