美文网首页
Objective-C 链式调用示例

Objective-C 链式调用示例

作者: Lee_Jo | 来源:发表于2020-04-08 15:28 被阅读0次

    Objective-C 链式调用

    .链式调用的特点:方法的返回值是block,block的返回值类型必须是类本身类型的指针,block的参数类型,就是方法需要操作的参数类型。

    #import <Foundation/Foundation.h>
    NS_ASSUME_NONNULL_BEGIN
    @interface Calculate : NSObject
    @property (nonatomic, assign) NSInteger result;
    - (Calculate*(^)(NSInteger))add;
    - (Calculate*(^)(NSInteger))sub;
    @end
    NS_ASSUME_NONNULL_END
    
    #import "Calculate.h"
    @implementation Calculate
    - (Calculate*(^)(NSInteger))add {
        return ^Calculate*(NSInteger valute) {
            self.result += valute;
            return self;
        };
    }
    - (Calculate*(^)(NSInteger))sub {
        return ^Calculate*(NSInteger value) {
            self.result -= value;
            return self;
        };
    }
    @end
    
    #import <Foundation/Foundation.h>
    #import "Calculate.h"
    NS_ASSUME_NONNULL_BEGIN
    @interface NSNumber (Math)
    + (NSInteger)makeCalculate:(void(^)(Calculate *make))calculate;
    @end
    
    #import "NSNumber+Math.h"
    @implementation NSNumber (Math)
    + (NSInteger)makeCalculate:(void (^)(Calculate *make))calculate {
        Calculate *operator = [[Calculate alloc] init];
        if (calculate) {
            calculate(operator);
        }
        return operator.result;
    }
    @end
    

    .调用示例

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
       NSInteger res = [NSNumber makeCalculate:^(Calculate * _Nonnull make) {
           make.add(3).add(8).sub(4);
       }];
        return YES;
    }
    

    相关文章

      网友评论

          本文标题:Objective-C 链式调用示例

          本文链接:https://www.haomeiwen.com/subject/frutmhtx.html