A.概念
1.block类似函数
(1)可以保存代码
(2)有返回值
(3)有形参
2.block的标志:^
1 // 没有参数和返回值的block 2 void (^myblock)() = ^{ // 没有形参,可以省略() 3 NSLog(@"这是新定义的block"); 4 }; 5 6 myblock(); 7 8 // 带参数和返回值的block 9 int (^sum)(int a, int b) = ^(int a, int b){ 10 return a + b; 11 }; 12 13 int c = sum(10, 11); 14 NSLog(@"%d", c);
3.可以访问代码块外的数据
1 int a = 10; 2 void (^block)(); 3 block = ^{ 4 NSLog(@"a = %d", a); 5 }; 6 block();
out:
2014-11-15 09:25:34.766 04-block[1355:303] a = 10
4.不能修改代码块外的局部变量
1 int a = 10; 2 void (^block)(); 3 block = ^{ 4 a = 20; // 默认情况下, block内部不能修改外面的局部变量 5 NSLog(@"a = %d", a); 6 }; 7 block();
解决:给局部变量加上”__block”(双下划线开头)关键字
1 __block int a = 10; 2 void (^block)(); 3 block = ^{ 4 a = 20; // error 5 NSLog(@"a = %d", a); 6 }; 7 block();
out:
2014-11-15 09:28:52.814 04-block[1376:303] a = 20
5.使用typedef
1 typedef int (^MyBlock) (int, int); 2 3 MyBlock sumBlock; 4 sumBlock = ^(int a, int b){ 5 return a + b; 6 }; 7 8 MyBlock minusBlock; 9 minusBlock = ^(int a, int b){ 10 return a - b; 11 };