Blocks模式
Blocks:带有自动变量的匿名函数,是C语言扩充功能。
c语言中 调用函数必须使用函数名称。举例如下:
int func(int count)
{
return count*count;
}
//c 函数调用type1
int m= func(99);
//c 函数调用type2
int (*ptr)(int)=&func; //返回值类型 (*指针)(函数参数类型)
int n=(*ptr)(13);
通过Blocks 可以使用匿名函数
- Blocks语法
* Block 类型变量
1、将Block语法赋值给声明为Block类型的变量
//1、定义Block类型变量 blk
int (^blk) (int) = ^(int event){
return event+1;
};
int x= blk(2);
NSLog(@"%i",x); //输出:3
//2、Block可以获取变量瞬时值
int count=5;
int (^blk) (int)= ^(int event){
return event+count;
};
count=10;
int x= blk(0);
NSLog(@"%i",x);
//结果:5 ; 因为blk截获的自动变量值为5;且不能给自动变量赋值(error)。
// 注:使用 __block说明符 可以改变blk中变量的值,且可以修改自动变量值。
2、Block类型做为函数参数。
demo:
//interface AAA:
-(void)testBlk:(void(^)(void))blkname;
-(void)testBlk2:(int(^)(int))blkname2 withBlkP:(int)p;
//implementation AAA:
-(void)testBlk:(void(^)(void)) blkname
{
blkname();
}
-(void)testBlk2:(int(^)(int))blkname2 withBlkP:(int)p
{
int res= blkname2(p);
NSLog(@"res=%d",res);
}
//test:
void (^blk0)(void)=^{
NSLog(@"blk..");
};
AAA *aa=[AAA new];
[aa testBlk:blk0];
int(^blk1)(int)=^(int k){
NSLog(@"blk.p=>%d",k);
return k*k;
};
[aa testBlk2:blk1 withBlkP:2];
3、Block类型做为函数返回值
demo:
//interface AAA:
-(int(^)(int))testReturnBlk;
//implementation AAA:
-(int(^)(int))testReturnBlk
{
return ^(int k){
return k*4;
};
}
//test:
int(^blkname3)(int)= [aa testReturnBlk];
int res= blkname3(9);
NSLog(@"result=>%d",res);
4、使用typedef简化 Block
demo:
typedef int(^blk_t)(int,int);
-(blk_t) testSamplifiedBlk;
-(blk_t) testSamplifiedBlk
{
return ^(int a,int b){
return a+b;
};
}
//test:
int(^blk4)(int,int)= [aa testSamplifiedBlk];
int res2= blk4(6,5);
NSLog(@"res2=>%d",res2);// 11
5、others
A、截获Objective-C对象可以使用但不能赋值;除非添加__block说明符
B、C语言数组截获并用下标(index)取值时报错;Block没有实现对C语言数组截获。可以用指针解决。
demo:
//报错
int age[3]={22,33,44};
void(^blk9)(void)=^{
int m=age[1];//Cannot refer to declaration with an array type inside block
NSLog(@"aaa %d",m);
};
blk9();
//正确
const char *test="hello world";
void(^blk9)(void)=^{
NSLog(@"%c",test[1]);
};
blk9();