Caret character between types rather than variables, surrounded by parentheses

被刻印的时光 ゝ 提交于 2019-11-26 12:32:22

问题


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))


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/3079624/caret-character-between-types-rather-than-variables-surrounded-by-parentheses

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