Objective-C 链式调用示例

Objective-C 链式调用

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

#import 
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 
#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 链式调用示例)