Block介绍(一)
一、概述
官方文档这是这样介绍block的
Block objects are a C-level syntactic and runtime feature. They
are similar to standard C functions, but in addition to
executable code they may also contain variable bindings to
automatic (stack) or managed (heap) memory. A block can
therefore maintain a set of state (data) that it can use to impact
behavior when executed.
简单的说Block是C语言级别的语法。它对比C,在栈内存跟堆内软的饮用中更佳灵活。并且,block可以做为参数来传值。
二、入门
- 语法
在这里定义了两个block,他的名字是myBlock,返回值是前面那个int,参数是它后面括号里面的int,等于号后面是方法体。
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};
typedef 下
typedef void (^BoolBlock)(BOOL);
//一个只接受一个BOOL参数,没有返回值的block
typedef int (^IntBlock)(void);
//一个没有参数,返回int的block
typedef BoolBlock (^HugeBlock)(IntBlock);
//看看,这个HugeBlock的参数和返回值都是block
三、例子
调用一下:
-(void)aMethod
{
BoolBlock ablock = ^(BOOL b) {
NSLog (@"Bool block !");
};
ablock(true);
}
作为参数返回一下:
typedef void (^BoolBlock) (BOOL);
- (BoolBlock)foo{
BoolBlock ablock = ^(BOOL b ){
NSLog(@"BOOL block!");
};
return ablock;
}
类的成员对象
@interface BlockTest : NSObject
typedef void (^BoolBlock)(BOOL);
@property (nonatomic,copy)BoolBlock block;
@end
BlockTest *t = [[BlockTest alloc]init];
t.block = ^(BOOL b){
NSLog(@"BlockTest block call");
};
t.block(true);
其他函数的参数
- (void)foo(BoolBlock block)
{
if (block) {
block();
}
}
其他block的参数
BoolBlock bBlock = ^(BOOL bV){if(Bv){/*do some thing*/}};
HugeBlock hBlock = ^(BoolBlock bB) {bB();};
hBolck(bBlock);
全局变量
static int(^maxIntBlock)(int, int) = ^(int a, int b){return a>b?a:b;};
int main()
{
printf("%d\n", maxIntBlock(2,10));
return 0;
}
这里我们可以看到block的用法跟函数其实没有太大的区别,但是在这里需要强调一下。在声明block的属性时,它的修饰符应该是copy
;
四、_block
在block内修改block之外的变量的时候,应该对变量天假_block标记。
__block int a = 0;
t.block = ^(BOOL b){
a++;
NSLog(@"BlockTest block call");
};