block在开发中的使用场景

2016-07-29  本文已影响40人  eightzg

block作为函数的参数

怎么判断参数是不是block
作为参数的block什么时候调用?
Paste_Image.png
什么时候把block设计成参数?
下面用block作为参数实现一个简单计算器
/** 保存计算结果 */
@property (nonatomic, assign) NSInteger result;

// 计算方法,接收一个结果参数,将计算后的新的结果值返回出去
- (void)cacultor:(NSInteger(^)(NSInteger result))cacultorBlock;

- (void)cacultor:(NSInteger (^)(NSInteger))cacultorBlock {
    //用if语句做判断,防止访问不存在的block造成的坏内存访问
    if (cacultorBlock) {
      _result =  cacultorBlock(_result);
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建计算器管理者
    CacultorManager *mgr = [[CacultorManager alloc] init];
    [mgr cacultor:^NSInteger(NSInteger result) {
        result += 5;
        result -= 2;
        result *= 4;
        result /= 2;
        return result;
    }];   
    NSLog(@"%zd",mgr.result);
}
Paste_Image.png

block作为函数的返回值

下面用block作为返回值实现一个复杂计算器
/** 结果 */
@property (nonatomic, assign) int result;

/** 有参数有返回值的加方法 */
- (CalculatorManager *(^)(int))add;
- (CalculatorManager *(^)(int))add
{
    //返回函数的返回值block
    return ^(int value){
        _result += value;
        //返回block的返回值CalculatorManager,在当前控制器就是self
        return self;
    };
}
- (void)viewDidLoad {
    [super viewDidLoad];
    CalculatorManager *mgr = [[CalculatorManager alloc] init];
    //当mgr.add(5)执行完之后result结果是5,同时block返回CalculatorManager,可以继续add(5)
    mgr.add(5).add(5).add(5).add(5);
    
    NSLog(@"%d",mgr.result);
}
上一篇 下一篇

猜你喜欢

热点阅读