Objective-C pass block as parameter

Jacksonkr picture Jacksonkr · Oct 29, 2011 · Viewed 97.1k times · Source

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

Jonathan Grynspan picture Jonathan Grynspan · Oct 29, 2011

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;