Asad Khan Asad Khan - 1 month ago 8
Objective-C Question

Caret character between types rather than variables, surrounded by parentheses

I was going through Apple's documentation and I saw something like this

(void (^)(void))
. Can somebody explain what this statement means?
^
is XOR, right?
void XOR void
doesn't makes much sense to me?

There was also something like
(void (^)(BOOL finished))

Answer

These are blocks which add anonymous functions and function objects to Objective-C. See e.g. Introducing Blocks and Grand Central Dispatch :

Block objects (informally, “blocks”) are an extension to C, as well as Objective-C and C++, that make it easy for programmers to define self-contained units of work. Blocks are similar to — but far more powerful than — traditional function pointers. The key differences are:

  • Blocks can be defined inline, as “anonymous functions.”
  • Blocks capture read-only copies of local variables, similar to “closures” in other languages

Declaring a block variable:

void (^my_block)(void);

Assigning a block object to it:

my_block = ^(void){ printf("hello world\n"); };

Invoking it:

my_block(); // prints “hello world\n”

Accepting a block as an argument:

- (void)doSomething:(void (^)(void))block;

Using that method with an inline block:

[obj doSomeThing:^(void){ printf("block was called"); }];
Comments