Jacksonkr Jacksonkr - 3 months ago 7
Objective-C Question

Objective-C pass block as parameter

How can I pass a

Block
to a
Function
/
Method
?

I tried
- (void)someFunc:(__Block)someBlock
with no avail.

ie. What is the type for a
Block
?

Answer

The type of a block varies depending on its arguments and its return type. In the general case, block types are declared the same way function pointer types are, but replacing the * with a ^. One way to pass a block to a method is as follows:

- (void)iterateWidgets:(void (^)(id, int))iteratorBlock;

But as you can see, that's messy. You can instead use a typedef to make block types cleaner:

typedef void (^ IteratorBlock)(id, int);

And then pass that block to a method like so:

- (void)iterateWidgets:(IteratorBlock)iteratorBlock;
Comments