Thursday August 22, 2013

What's With The Crazy Objective-C Block Syntax

Thanks to Nils Hayat, the mysteries of the Objective-C block syntax are laid bare before my eyes:

As convoluted as it may seem, blocks syntax in Objective-C is built upon standard C syntax. A block in Objective-C is nothing more than a pointer to a function that captures its scope. Once you understand that and practice writing and reading a few blocks declaration, you’ll find it much easier to apprehend.

He walks through the basic C declaration syntax and describes the history of the block declaration modifier, the beloved caret: ^. I finally understand why the name of the block has to go within the first set of parenthesis, as in int (^blockName)(int argument). I’ve used C for a long time but never had to think about the precedence rules for declarators. After reading through Nils’ excellent summary, I don’t think I’ll need to look up the syntax again.

(via @orta)