Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

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:

void (^blockPtrVar) (NSString *arg) = ^(NSString *arg) { NSLog (@"%@", arg); };

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

Invoke it like a function pointer:

blockPtrVar (@"hello");

which prints "hello."

Things become more readable when you use a typedef:

typedef void (^BlockType) (NSString *arg);

BlockType blockPtrVar = ^(NSString *arg) { NSLog (@"%@", arg); };

blockPtrVar (@"there");

which prints out "there" as you would expect.

  • + Share This
  • 🔖 Save To Your Account