block之---应用场景:做参数和返回值

1.做参数
什么时候使用Block充当参数?

封装一个功能,这个功能做什么事情由外界决定,但是什么时候调用由内部决定,这时候就需要把Block充当参数去使用.

模拟需求:

封装一个计算器,怎么计算由外界决定,什么时候计算由内部决定

// 声明计算器类
@interface CaculatorManager : NSObject @property (nonatomic, assign) int result; // 声明方法:参数为block类型 - (void)caculator:(int(^)(int result))caculatorBlock; @end ****************************************************** // 实现计算器类 @implementation CaculatorManager // 实现方法 - (void)caculator:(int (^)(int))caculatorBlock { // 调用block _result = caculatorBlock(_result); } ****************************************************** // 使用计算器类 @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 创建类 CaculatorManager *mgr = [[CaculatorManager alloc] init]; // 使用方法,传入自定义的block [mgr caculator:^(int result){ result += 5; result *= 5; return result; }]; NSLog(@"%d",mgr.result); } @end 
2.做返回值
模拟需求:

封装一个计算器,实现加法计算,在外部使用加法方法时可以实现链式编程。

// 声明计算器类
@interface CaculatorManager : NSObject @property (nonatomic, assign) int result; // 声明加法方法:返回值为block类型 - (CaculatorManager *(^)(int))add; @end ****************************************************** // 实现计算器类 @implementation CaculatorManager // 实现方法 - (CaculatorManager * (^)(int))add { // 返回加法计算的block,并且block的返回值为计算器类 return ^(int value){ _result += value; return self; }; } ****************************************************** // 使用计算器类 @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 创建类 CaculatorManager *mgr = [[CaculatorManager alloc] init]; // 使用链式编程的方式调用方法 mgr.add(5).add(6).add(7); NSLog(@"%d",mgr.result); } @end

 

转载于:https://www.cnblogs.com/mengfei90/p/5145826.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值