python链式编程_1.RAC解析 - 自定义链式编程

目的

模仿Masonry连续运用点语法的操作

[self.view mas_makeConstraints:^(MASConstraintMaker *make) {

make.top.equalTo(@10).offset(1);

}];

写出一个连加的操作

make.add(10).add(10);

想看结果的请直接跳到“最终结果”

分析

一.定义SQMath类

SQMath.h

#import

@interface SQMath : NSObject

- (NSInteger)result;

- (void)add:(int)number;

@end

SQMath.m

#import "SQMath.h"

@interface SQMath ()

@property (nonatomic, assign) NSInteger number;

@end

@implementation SQMath

- (NSInteger)result {

return self.number;

}

- (void)add:(int)number {

self.number += number;

}

@end

使用这个SQMath的add方法

SQMath *math = [[SQMath alloc] init];

[math add:10];

[math add:20];

NSLog(@"%ld", [math result]);

二.将函数调用改为点语法

如果要用点语法,需要让-add从一个方法变成一个add的属性。但是这样就没有办法传参了

- (NSInteger)add;

但是如果返回值是一个 NSInteger (^)(NSInteger) 类型的block就可以了。math.add返回的是这个block,这个block是需要一个NSInteger为参数(加数),返回值是NSInteger(结果)。

SQMath.m

- (NSInteger (^)(NSInteger count))add {

__weak typeof(self) weakSelf=self;

NSInteger (^addBlock)(NSInteger) = ^(NSInteger addCount){

__strong typeof(weakSelf) strongSelf = weakSelf;

strongSelf.number += addCount;

return strongSelf.number;

};

return addBlock;

}

或者

- (NSInteger (^)(NSInteger count))add {

__weak typeof(self) weakSelf=self;

return ^(NSInteger addCount) {

__strong typeof(weakSelf) strongSelf = weakSelf;

strongSelf.number += addCount;

return strongSelf.number;

};

}

使用这个SQMath的add方法

SQMath *math = [[SQMath alloc] init];

NSLog(@"%ld", math.add(10));

NSLog(@"%ld", math.add(20));

NSLog(@"%ld", math.add(30));

三.连续使用点语法

只要将Block的返回值更改为self。这样每次add返回的则变成了SQMath的实例对象,这样就可以实现连续点语法的效果了。

- (SQMath* (^)(NSInteger count))add {

__weak typeof(self) weakSelf=self;

return ^(NSInteger addCount) {

__strong typeof(weakSelf) strongSelf = weakSelf;

strongSelf.number += addCount;

return self;

};

}

使用这个SQMath的add方法

SQMath *math = [[SQMath alloc] init];

NSLog(@"%ld", math.add(10).add(20).add(30).result) ;

四.将这个改为NSNumber的Category

NSNumber+SQMath.h

#import

#import "SQMath.h"

@interface NSNumber (Math)

- (NSInteger)sq_add:(void(^)(SQMath *make))block;

@end

NSNumber+SQMath.m

#import "NSNumber+SQMath.h"

@implementation NSNumber (SQMath)

- (NSInteger)sq_add:(void(^)(SQMath *))block {

SQMath *math = [[SQMath alloc] init];

block(math);

return math.result;

}

@end

NSNumber+SQMath 使用

NSInteger result = [@10 sq_add:^(SQMath * make) {

make.add(10).add(20);

}];

NSLog(@"%ld", result);

最终结果

ps:链式编程什么时候用我还真不太清楚,但我知道面试的时候肯定有用 哈哈。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值