如何使用ARC将块实例化为实例变量?

Pio*_*sik 2 objective-c objective-c-blocks

做一件像这样的工作怎么办?

void (^)(void) *someBlock = ^{
  //some code
};
Run Code Online (Sandbox Code Playgroud)

Joh*_*rug 7

德米特里的答案是完全正确的.将块语法看作C函数声明:

// C function -> <return type> <function name> (<arguments>)
void someFunction(void) 
{
  // do something
}

// block -> <return type> (^<block variable name>) (<arguments>)
void (^someBlock)(void) = ^{
    // do something
};
Run Code Online (Sandbox Code Playgroud)

另一个例子:

// C function
int sum (int a, int b)
{
    return a + b;
}

// block
int (^sum)(int, int) = ^(int a, int b) {
    return a + b;
};
Run Code Online (Sandbox Code Playgroud)

因此,只需将块语法视为C函数声明:首先是返回类型int,然后是块变量的名称,(^sum)然后是参数类型列表(int, int).

但是,如果您的应用中经常需要某种类型的块,请使用typedef:

typedef int (^MySumBlock)(int, int);
Run Code Online (Sandbox Code Playgroud)

现在您可以创建MySumBlock类型的变量:

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;
};
Run Code Online (Sandbox Code Playgroud)

希望有帮助:)