如何使用ARC将一个块实例化为实例变量? [英] How does one instantiate a block as an instance variable using ARC?
本文介绍了如何使用ARC将一个块实例化为实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要做什么才能使这种工作正常进行?
What does one do to make something like this work?
void (^)(void) *someBlock = ^{
//some code
};
推荐答案
德米特里(Dmitry)的答案完全正确.将块语法视为C函数声明:
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
};
另一个例子:
// C function
int sum (int a, int b)
{
return a + b;
}
// block
int (^sum)(int, int) = ^(int a, int b) {
return a + b;
};
因此,只需将块语法视为C函数声明即可:
首先是返回类型int
,然后是块变量(^sum)
的名称,然后是参数类型(int, int)
的列表.
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)
.
但是,如果您经常在应用中需要某种类型的阻止,请使用typedef:
If, however, you need a certain type of block frequently in your app, use a typedef:
typedef int (^MySumBlock)(int, int);
现在您可以创建MySumBlock
类型的变量:
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;
};
希望有帮助:)
这篇关于如何使用ARC将一个块实例化为实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文