#import <Foundation/Foundation.h>
//定义一种block类型
typedef int(^compatetor)(int arg1, int arg2);
//实例化一个block对象
compatetor comp = ^(int arg1, int arg2){
int result = 0;
if(arg1 > arg2) {
result = arg1;
} else {
result = arg2;
}
return result;
};
//正常的定义及实现block方法
int(^minvalue)(int, int) = ^(int inputa, int inputb){
return MIN(inputa, inputb);
};
int main(int argc, const char * argv[]) {
@autoreleasepool {
//a 值不可以变
int a = 20;
int(^blka)(void) = ^(){
return a;
};
blka();
NSLog(@"The a value could not be changed %d", blka());
//b 值可以改变
__block int b = 20;
int(^blkb)(void) = ^(){
b = 40;
return b;
};
blkb();
NSLog(@"The b value could be changed %d", blkb());
NSLog(@"the max value is %d", comp(33, 203));
NSLog(@"The min value is %d", minvalue(33,102));
}
return 0;
}
Result:
2018-03-17 15:30:28.139641+0800 TOCBlockc[26893:1809406] The a value could not be changed 20
2018-03-17 15:30:28.139919+0800 TOCBlockc[26893:1809406] The b value could be changed 40
2018-03-17 15:30:28.139942+0800 TOCBlockc[26893:1809406] the max value is 203
2018-03-17 15:30:28.139956+0800 TOCBlockc[26893:1809406] The min value is 33
Program ended with exit code: 0