1.使用typedef定义block
typedef int(^Easyblock) (int,int);
Easyblock block1 = ^int(int x,int y){
return x * y;
};
Easyblock block2 = ^int(int x,int y) {
return x / y;
};
NSLog(@"Easyblock1 = %d",block(2,3));
NSLog(@"Easyblock2 = ",block2(6,3));
2.block与局部变量
(1) 在block中可以访问外部的局部变量
float a = 3.3;
void(^testBlock)(float) = ^void(float c){
NSLog(@"%.2f",c +a);
};
testBlock(3.12);
(2) 如果需要在block内部修改局部变量的值,就在局部变量定义时前面加上修饰符 __block;
__block int d = 5;
void(^testBlock1)(int) = ^void(int num1){
d += 10;
NSLog(@"d1 = %d",d1 + num1);
}
tetBlock(20);
3.block与全局变量
全局变量是在main函数之外定义的变量,不需要加 __block 就可以在 block内部修改
int (^block3)(int) = ^int(int num2){
num++; // num是在main函数前定义的变量 num = 10;
return num2 +=num;
};
NSLog(@"num2 = %d",block(12));