Block 学习

2016-05-18  本文已影响22人  CoderChou

block 构成部分

^(参数列){行为主体};           例如:^(int a) {return a*a};

block Pointer

回传值(^名字)(参数列);

int (^ square ) (int) ;

以上是一个bool型的变量

//定义一个bool类型的block变量;

BOOL(^isInputEven)(int) = ^(intinput){

if(input%2==0) {

returnYES;

}else{

returnNO;

}

};

//调用block

NSString*number = isInputEven(index) ?@"is an even":@"is not even";

NSLog(@"-----%@",number);//应该输出 is not even

//block外的price能在block内部使用

floatprice =1.99;

float(^finalPrice)(int) = ^(intquantity){

//在block内的price是readonly的

returnquantity * price;

};

intorderQuantity =10;

floatfinal = finalPrice(orderQuantity);

NSLog(@"final--------%f",final);

讲局部变量声明为__block,表示外部变化将在block内进行同样操作,比如:

上一篇下一篇

猜你喜欢

热点阅读