前言
最近对Masonry的链式句法很感兴趣,于是尝试自己实现该效果.我是做了一个加法器,用法如下:
int result = [NSObject makeCaculator:^(CaculatorMaker *make) {
make.add(2).add(4);
}];
NSLog(@"result is %d", result);
打印结果:
2016-02-20 15:18:17.178 练习链式语法封装[30206:1952288] result is 6
思路
实现链式句法主要原理是利用OC的block特性,add
是make
对象的一个block属性,定义如下:
@property (copy, nonatomic, readonly) CaculatorMaker *(^add)(int);
该block属性以block的形式被调用时,会用到一个int
参数,返回一个CaculatorMaker
对象(其实是返回的self),然后返回的CaculatorMaker
对象可以再次调用自己的add属性,从而达到链式句法的效果
具体实现
- NSObject+Caculator.h 文件
#import <Foundation/Foundation.h>
@class CaculatorMaker;
//NSObject类的拓展
@interface NSObject (Caculator)
+ (int)makeCaculator:(void (^)(CaculatorMaker *make)) caculatorBlock;
@end
//CaculatorMaker类的声明
@interface CaculatorMaker : NSObject
@property (assign, nonatomic) int result;
@property (copy, nonatomic, readonly) CaculatorMaker *(^add)(int);
@end
- NSObject+Caculator.m 文件
#import "NSObject+Caculator.h"
@implementation NSObject (Caculator)
+ (int)makeCaculator:(void (^)(CaculatorMaker *))caculatorBlock {
CaculatorMaker *make = [CaculatorMaker new];
caculatorBlock(make);
return make.result;
}
@end
@implementation CaculatorMaker
- (instancetype)init
{
self = [super init];
if (self) {
self.result = 0;
}
return self;
}
- (CaculatorMaker *(^)(int))add {
return ^(int a){
self.result += a;
return self;
};
}
@end
后记
希望和大家共同学习,其实我是来practice markdown的O(∩_∩)O~
网友评论