title: iOS 连式语法
date: 2016-05-04 20:58:26
tags:
@interface NSObject (LianShi)
+ (int)makeCalculate:(void (^)(CaculatorMaker *))block;
@end
@implementation NSObject (LianShi)
// 定义事件
+ (int)makeCalculate:(void (^)(CaculatorMaker *))block
{
CaculatorMaker *caculatorMaker = CaculatorMaker.new;
if (block) {
block(caculatorMaker);
}
return caculatorMaker.all;
}
@end
@interface CaculatorMaker : NSObject
/** <##> */
@property int all;
- (CaculatorMaker *(^)(int value, int value2))add;
- (CaculatorMaker *(^)(int))sub;
@end
@implementation CaculatorMaker
- (CaculatorMaker *(^)(int value, int value2))add
{
// return一个匿名block,参数int类型,block返回类型 CaculatorMaker *
return ^CaculatorMaker *(int value, int value2) {
NSLog(@"%d %d", value, value2);
_all += value;
return self;
};
}
- (CaculatorMaker *(^)(int))sub
{
return ^CaculatorMaker *(int value) {
NSLog(@"%d", value);
_all += value;
return self;
};
}
@end
// 用法
int all = [NSObject makeCalculate:^(CaculatorMaker *caculatorMaker) {
caculatorMaker.add(2, 3).sub(5);
}];
NSLog(@"%d", all);