How does one instantiate a block as an instance variable using ARC?

亡梦爱人 提交于 2019-12-13 16:39:37

问题


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

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