O'Reilly logo

Advanced Mac OS X Programming: The Big Nerd Ranch Guide by Mark Dalrymple

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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​ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required