问题
What does one do to make something like this work?
void (^)(void) *someBlock = ^{
//some code
};
回答1:
Dmitry's answer is exactly right. Think of the block syntax as a C function declaration:
// C function -> <return type> <function name> (<arguments>)
void someFunction(void)
{
// do something
}
// block -> <return type> (^<block variable name>) (<arguments>)
void (^someBlock)(void) = ^{
// do something
};
Another example:
// C function
int sum (int a, int b)
{
return a + b;
}
// block
int (^sum)(int, int) = ^(int a, int b) {
return a + b;
};
So just think of the block syntax as a C function declaration:
First the return type int
, then the name of the block variable (^sum)
and then the list of arguments types (int, int)
.
If, however, you need a certain type of block frequently in your app, use a typedef:
typedef int (^MySumBlock)(int, int);
Now you can create variables of the MySumBlock
type:
MySumBlock debugSumBlock = ^(int a, int b) {
NSLog(@"Adding %i and %i", a, b);
return a + b;
};
MySumBlock normalSumBlock = ^(int a, int b) {
return a + b;
};
Hope that helps :)
回答2:
Just block syntax
void (^someBlock)(void) = ^{
//some code
};
来源:https://stackoverflow.com/questions/16164928/how-does-one-instantiate-a-block-as-an-instance-variable-using-arc