Declaring Blocks in Objective-C
Blocks in Objective-C are super useful for making your object-oriented code a bit more functional. But as blocks are an extension to the C language, they have to play by the rules of C, so the syntax is a little obscure, and the documentation can be a little hard to find. So here’s a guide on how to declare blocks so you can use them in various scenarios.
The standard way of declaring a block:
The order here is return type, then the block name, then the parameters, or void if you have none. Counterintuitively, the variable name is NOT the last thing on the list. It comes after the
^ which accompanies blocks. Parentheses are significant, so don’t forget them. You can also add or remove whitespace between anything. When declaring a block like this, you can supply names for the parameters, or omit them. They’re a good thing to add, though; if you use Xcode to autocomplete one of these, it will include the parameter names in the autocompleted method call, and omit them (leading to compile errors you have to manually fix) if you don’t.
If you find yourself using a block type in more than one place, you can make it a typedef. Xcode even has a handy autocomplete for this, by typing
typedefBlock and autocompleting, you’ll get a template that is way easier to use than remembering all this stuff. Then you can reference it like any other typedef. Again, parentheses are significant, whitespace is not.
C Function Parameters:
Objective-C Method Parameters:
Note: When writing method signatures that include blocks, you do NOT include the name after the
^ declaration. Instead, you include it like any other Objective-C method parameter name, just outside of the type’s parentheses.
So there you have it. Those are the most common cases for declaring Objective-C blocks. Go forth and do evil with them. For more information on blocks, see Apple’s Blocks Programming Guide and Apple’s Short Practical Guide to Blocks.