- #import <Foundation/Foundation.h>
 
  
- int sum(int a, int b){
 
 -     return a+b;
 
 - }
 
 - // p是一个指向函数的指针,p指向的函数具有两个int类型的参数,返回值为int类型
 
 - int (*p)(int a,int b);
 
  
- // typedef可以自定义数据类型
 
 - // 定义一个类型P:表示指向函数的指针
 
 - typedef int (*P)(int a, int b);
 
  
- // 定义了一个数据类型MyBlock 表示一个具有int类型返回值,两个int类型参数的block类型
 
 - typedef int(^MyBlock)(int a,int b);
 
  
- int main()
 
 - {    
 
 -     // 将指针p指向函数sum
 
 -     p = sum;
 
 -     //向p指向的函数内传递参数1,2 获取函数返回值,结果是3  相当于sum(1,2);
 
 -     p(1,2);
 
 -     
 
 -     // sumBlock是一个block类型的数据
 
 -     int (^sumBlock)(int a,int b);
 
 -     // sumBlock 内封装的代码是 return a+b;
 
 -     sumBlock = ^(int a,int b){
 
 -         return a+b;
 
 -     };
 
 -     // 调用sumBlock得到 return a+b;  的值,  等于3
 
 -     sumBlock(1,2);
 
 -     
 
 -     
 
 -     
 
 -     // P p1就等于int(*p1)(inta,int b)
 
 -     P p1 = sum;
 
 -     
 
 -     p1(1,2);
 
 -     
 
 -     // 定义一个MyBlock类型的变量b1 相当于 int (^b1)(int a,int b)
 
 -     MyBlock b1 = ^(int a,int b){
 
 -         return a+b;
 
 -     };
 
  
-     b1(1,2);
 
 -     
 
 -     NSLog(@"p = %d,sumBlock = %d,p1 = %d,b1 = %d",p(1,2),sumBlock(1,2),p1(1,2),b1(1,2));
 
  
-     return 0;
 
 - }
 
 
  复制代码 
 
需要注意的就是在block封装的代码块内可以访问代码块外面的变量,但是不能修改外面的局部变量。如果需要修改某局部变量,则要给该变量前面加上__block关键字:如 __block int c = 3; 这里下划线是双下划线 |