zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    C# 设计模式之简单工厂模式
    CentOS7下二进制文件安装MySQL5.6
    CentOS7下源码安装5.6.23
    CentOS7下yum方式安装mysql5.6
    关于网页图标使用与字体图标制作
    【canvas系列】canvas实现“ 简单的Amaziograph效果”--画对称图【强迫症福利】
    【canvas系列】canvas实现"雷达扫描"效果
    【canvas系列】用canvas实现一个colorpicker(类似PS的颜色选择器)
    如何在vue自定义组件中使用v-model
    webpack4 splitChunksPlugin && runtimeChunkPlugin 配置杂记
  • 原文地址:https://www.cnblogs.com/mengfei90/p/5145826.html
Copyright © 2011-2022 走看看