English 中文(简体)
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))

最佳回答

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

Invoking it:

my_block(); // prints “hello world
”

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.





相关问题
How to change out-of-focus text selection color in Xcode?

Okay, I ll bite. I ve got really pleasant code/window colors set up in Xcode. Ordinarily, my selection color is very visible. When I am doing a project search and iterating through the results, ...

pdo database abstraction

Can someone help me to see what is going wrong with this setup I build the @sql query in the function below like this. The extra quotes are setup in the conditions array. $sql .= " WHERE $...

I wish I could correlate an "inline view"

I have a Patient table: PatientId Admitted --------- --------------- 1 d/m/yy hh:mm:ss 2 d/m/yy hh:mm:ss 3 d/m/yy hh:mm:ss I have a PatientMeasurement table (0 to ...

Syntax help! Php and MYSQL

Original: $sql = "SELECT DATE(TimeAdded) AS Date, $column_name FROM Codes ORDER BY TimeAdded ASC"; Altered: $sql = "SELECT DATE("m", TimeAdded ) AS Date, ColumnName FROM TableName ORDER BY ...

Is this code Equivalent

I am not a fan of the following construction if (self = [super init]) { //do something with self assuming it has been created } Is the following equivalent? self = [super init]; if (self != ...

热门标签