1.RAC解析 – 自定义链式编程

目的
模仿Masonry连续运用点语法的操作
[self.view mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(@10).offset(1);
}];
写出一个连加的操作
make.add(10).add(10);

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

分析
一.定义SQMath类
SQMath.h
#import <Foundation/Foundation.h>

@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 <Foundation/Foundation.h>
#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);
最终结果
SQChainProgramming
ps:链式编程什么时候用我还真不太清楚,但我知道面试的时候肯定有用 哈哈。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理