iOS之Block

来源:互联网 发布:淘宝专业刷单团队 编辑:程序博客网 时间:2024/05/31 00:40

1.Block

Block 一般又block pointer 和 block实体组成。

int (^ square) (int);//block pointer;声明block,

square = ^(int a) { return a*a;}//block 实体;

2.在objective C 中声明方法:

-(void) objcMethod :(int (^)(int)) square;

?为什么方法的返回值是void 而block 作为传入参数square的返回值是int,

同时 int (^ square) (int )这种声明方法和 (int (^) (int)) square也有一些区别。这是要特别注意的地方。

而在实现方法时,采用的是………^(int id){  主体};

比如在NSArray中的遍历方法

[test enumrateObjectsUsingBlock:^(id obj,NSInteger idx,BOOL * stop ) {主体;}];

3.存取可变变量和存取不可变变量

不可变变量:

  1. {  
  2.     int outA = 8;  
  3.     int (^myPtr)(int) = ^(int a){ return outA + a;};  
  4.     //block里面可以读取同一类型的outA的值  
  5.     int result = myPtr(3);  // result is 11  
  6.     NSLog(@"result=%d", result);  
  7. }  

可变变量:

  1. {  
  2.     static int outA = 8;  
  3.     int (^myPtr)(int) = ^(int a){return outA + a;};  
  4.     outA = 5;  
  5.     int result = myPtr(3);  //result的值是8,因为outA是static类型的变量  
  6.     NSLog(@"result=%d", result);  
  7.       
  8. }  
4.Block Variable 类型的变量_block;

_block int num;

作用同可变变量。



0 0
原创粉丝点击