Copyright © 2017年ZaneWangWang. All rights reserved.
如果你看到的不是简书原文请点击查看原文
说到链式编程在iOS中我们首先想到的应该就是masonry框架,示例如下图:
这种打点式的代码风格会使得我们的代码的可读性很好,下边我们就来写一个计算器的例子来剖析一下链式编程的思想.
1.首先创建一个NSobject类别Calculator,并在其中创建Calculator类
.h内容如下:
//
//NSObject+Calculator.h
//Created by iOS on 17/2/28.
//Copyright © 2017年iOS. All rights reserved.
//
#import <Foundation/Foundation.h>
@classCalculator;
typedefvoid(^Mask)(Calculator*calculator);
@interfaceNSObject (Calculator)
//加法
+ (float)calculatorNumber:(Mask)calculator;
@end
@interface Calculator :NSObject
@property(nonatomic,assign)floatvalue;
- (Calculator*(^)(float))add;
- (Calculator*(^)(float))min;
- (Calculator*(^)(float))mul;
- (Calculator*(^)(float))div;
@end
.m内容如下
//
//NSObject+Calculator.m
//Created by iOS on 17/2/28.
//Copyright © 2017年iOS. All rights reserved.
//
#import"NSObject+Calculator.h"
@implementationNSObject (Calculator)
+ (float)calculatorNumber:(Mask)calculator{
Calculator*cal = [[Calculatoralloc]init];
calculator(cal);
return cal.value;
}
@end
@implementationCalculator
-(Calculator*(^)(float))add{
return^(floatvalue){
_value+= value;
returnself;
};
}
-(Calculator*(^)(float))min{
return^(floatvalue){
_value-= value;
returnself;
};
}
-(Calculator*(^)(float))mul{
return^(floatvalue){
_value*= value;
returnself;
};
}
-(Calculator*(^)(float))div{
return^(floatvalue){
_value/= value;
returnself;
};
}
@end
2.测试代码如下: