views:

108

answers:

2

I was going through Apple's documentation & 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))

+9  A: 

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"); }];
Georg Fritzsche
Thank you guys...you're my heros ;)
Asad Khan
+1  A: 

That's a block, an Apple-specific extension to C, similar to function pointers, or function objects in other languages.

(void (^)(void)) looks like a typecast to the type of a block that takes no parameters and returns nothing. Similarly, (void (^)(BOOL finished)) looks like another typecast, to a block with one boolean parameter and returning nothing.

ptomato