Block Variables

Blocks are not limited to living in-line in method or function calls. You can have variables, whether local, global, or instance, that point to blocks. The syntax is like standard C function pointer syntax but using a caret instead of a star:

v​o​i​d​ ​(​^​b​l​o​c​k​P​t​r​V​a​r​)​ ​(​N​S​S​t​r​i​n​g​ ​*​a​r​g​)​ ​=​ ​^​(​N​S​S​t​r​i​n​g​ ​*​a​r​g​)​ ​{​ ​N​S​L​o​g​ ​(​@​"​%​@​"​,​ ​a​r​g​)​;​ ​}​;​

The name of the variable is blockPtrVar. The block returns nothing (void) and takes a single NSString argument.

Invoke it like a function pointer:

b​l​o​c​k​P​t​r​V​a​r​ ​(​@​"​h​e​l​l​o​"​)​;​

which prints hello.

Things become more readable when you use a typedef:

t​y​p​e​d​e​f​ ​v​o​i​d​ ​(​^​B​l​o​c​k​T​y​p​e​)​ ​(​N​S​S​t​r​i​n​g​ ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.