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