Caret character between types rather than variables, surrounded by parentheses

戏子无情 提交于 2019-11-27 02:12:45
Georg Fritzsche

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"); }];

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!