#import "ViewController.h"
//声明 返回值为int 两个参数的block 别名为Addition 之后可以用Addition声明变量
typedef int(^Addition)(int a,int b);
//声明 返回值为int 两个参数的block 别名为Multiplication 之后可以用Multiplication声明变量
typedef int(^Multiplication)(int a,int b);
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
{
//返回值是int类型 名字是count 参数是两个int类型 的block
int (^count)(int,int) = ^(int a,int b){
return a + b;
};
NSLog(@"8 + 7 = %d",count(8,7));
//block作为变量赋值
int (^count2)(int,int);
count2 = count;
NSLog(@"15 + 15 = %d",count2(15,15));
//block作为函数参数
[self myCount:^int(int a, int b) {
return a + b;
}];
//block作为返回值
count2 = [self returnMyBlock];
NSLog(@"15 * 15 = %d",count2(15,15));
}
{
//使用别名声明block变量
Addition add1 = ^(int a,int b){
return a + b;
};
Multiplication mult1 = ^(int a,int b){
return a*b;
};
NSLog(@"666 + 666 = %d",add1(666,666));
NSLog(@"666 * 1 = %d",mult1(666,1));
//作为参数
[self logAdd:add1];
//作为返回值
Multiplication mult2 = [self myMult];
NSLog(@"100 * 199 = %d",mult2(100,100));
}
{
//block截取自动变量
int a = 10;
int b = 99;
//block截取了此刻a,b的值
int(^add)() = ^{
//a = 88;报错
//b = 66;
return a+b;
};
a = 0;
b = 0;
//上面修改a,b的值不影响block的执行结果
NSLog(@"count : %d",add());
}
{
//__block修饰符
__block int a = 10;//a,b的值为10,99 顺序1
__block int b = 99;
//__block修饰符
int(^add)() = ^{
a = 88;//a,b的值为88,66 顺序3
b = 66;
return a+b;
};
a = 0;//a,b的值为0,0 顺序2
b = 0;
//log为 add : 154
NSLog(@"count : %d",add());
}
}
- (void)myCount:(int(^)(int,int)) countBlock{
NSLog(@"30 + 30 = %d",countBlock(30,30));
}
- (int(^)(int,int))returnMyBlock{
return ^(int a,int b){
return a*b;
};
}
- (void)logAdd:(Addition)add{
NSLog(@"100 + 100 = %d",add(100,100));
}
- (Multiplication)myMult{
Multiplication mult = ^(int a,int b){
return a*b;
};
return mult;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Block学习笔记二之几个简单的Block(贴代码)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1-晨奶跟进:最近可以五点半吃了,虽然之前还会起来哭着要吃,但是耐心哄哄还是可以睡的,好的时候可以五点多一点起来,...