1.什么是Blocks
Blocks 是C预言的扩充功能,简单来说就是带有自动变量(局部变量)的匿名函数,一般来说,blocks包含的内容可以理解为代码块。
2.Blocks 模式
2.1 Block 语法
^ void(int value) { }
其中对应关系为 ^ +返回值类型+参数列表+表达式 也可以缩写为
^ (int value) { }
2.2 Block的函数传递
int (^blk)(int) = ^ (int value){ return value+1; };
int (^blk1)(int) = blk;
int (^blk2)(int) = blk1;
blk2 = blk1;
//通过typedef 可以声明blk_t类型变量
typedef int (^blk_t)(int) ;
blk_t blk = ^(int value){ return value+1; };
2.3 Block截取自动变量
int blkValue = 2;
NSString *blkStr = [NSString stringWithFormat:@"my blkValue is :%d",blkValue];
void (^blk)(void) = ^{
NSLog(@"blkStr = %@",blkStr);
};
blkValue = 3;
blkStr = [NSString stringWithFormat:@"my blkValue is :%d",blkValue];
blk();
打印如下 blkValue 的值被截获
blkStr = my blkValue is :2
3.Block中改变变量值
如果在Block块之外给变量赋值,如下代码会产生编译错误,需要加__block说明符
int blkValue = 2;
NSString *blkStr = [NSString stringWithFormat:@"my blkValue is :%d",blkValue];
void (^blk)(void) = ^{
blkValue = 3;
NSLog(@"blkStr = %@",blkStr);
};
blkValue = 3;
blkStr = [NSString stringWithFormat:@"my blkValue is :%d",blkValue];
blk();
__block int blkValue = 2;
NSString *blkStr = [NSString stringWithFormat:@"my blkValue is :%d",blkValue];
void (^blk)(void) = ^{
blkValue = 3;
NSLog(@"blkStr = %@",blkStr);
};
blkValue = 3;
blkStr = [NSString stringWithFormat:@"my blkValue is :%d",blkValue];
blk();