OC block小記

 1 // block語法(可定義在任意位置)
 2         //1.定義
 3         int (^Sum)(int, int) = ^(int a, int b){return a+b;};
 4         
 5         //2.使用
 6         NSLog(@"sum = %d", Sum(10, 20));
 7         
 8         //3.將block定義成類型
 9         typedef int(^myBlock)(int, int);
10         //4.定義block類型的變量
11         myBlock sub = ^(int a, int b){return a-b;};
12         myBlock mul = ^(int a, int b){return a*b;};
13         
14         NSLog(@"sub=%d", sub(10, 20));
15         NSLog(@"mul = %d", mul(10, 20));
16         
17         //5.block和局部變量的關係
18         //5.1 在block中能夠訪問局部變量
19         int a = 20;
20         int b = 10;
21         void(^myBlock2)() = ^(){
22             NSLog(@"a+b = %d", a+b);
23         };
24         myBlock2();
25         //5.2 在block中不能修改局部變量的值
26         void (^myBlock3)() = ^(){
27             //a = 30;     //error:普通變量不能修改
28         };
29         //5.3 在block中能夠修改用__block修飾的變量的值
30         __block int c = 30;
31         void (^myBlock4)() = ^(){
32             c = 40;
33             NSLog(@"c = %d", c);
34         };
35         myBlock4();
相關文章
相關標籤/搜索