# 1,链式编程思想:是将多个操作(多行代码)通过点号(.)链接在一起成为一句代码,使代码可读性提高。
2,链式编程特点:方法的返回值是block,block必须返回对象本身(返回block时,block所在的方法调用者对象)block的参数是需要操作的值。
经典:masonry 框架
代码实例:简易计算器
- (void)viewDidLoad {
[super viewDidLoad];
int result = [CalculateManager zwg_makeCalculates:^(CalculateManager *make) {
make.add(10).add(10);
make.div(2);
make.multi(10).minus(2);
}];
}
CalculateManager.h 文件中
#import
@interfaceCalculateManager :NSObject
@property (nonatomic, assign) int result;
@property (nonatomic, copy) NSString *name;
- (CalculateManager*(^)(intnum))add;// 加
- (CalculateManager*(^)(intnum))minus;// 减
- (CalculateManager*(^)(intnum))multi;//乘
- (CalculateManager*(^)(intnum))div;//除
CalculateManager.m 文件中
#import "CalculateManager.h"
@implementationCalculateManager
- (CalculateManager *(^)(int))add {
return ^CalculateManager *(int num) {
self.result+= num;
NSLog(@"add : %d",self.result);
return self;
};
}
- (CalculateManager*(^)(int))minus {
return ^CalculateManager *(int num) {
self.result-= num;
NSLog(@"minus : %d",self.result);
return self;
};
}
- (CalculateManager*(^)(int))multi {
return ^CalculateManager *(int num){
self.result*= num;
NSLog(@"multi : %d",self.result);
return self;
};
}
- (CalculateManager *(^)(int))div {
return ^CalculateManager *(int num) {
self.result/= num;
NSLog(@"div : %d",self.result);
return self;
};
}
NSObject+Calculate.h 文件
#import
@class CalculateManager;
@interfaceNSObject (Calculate)
+ (int)zwg_makeCalculates:(void(^)(CalculateManager*make))block;
@end
NSObject+Calculate.m 文件
#import "NSObject+Calculate.h"
#import "CalculateManager.h"
@implementationNSObject (Calculate)
+ (int)zwg_makeCalculates:(void(^)(CalculateManager*make))block {
CalculateManager *calculate = [[CalculateManager alloc] init];
block(calculate);
returncalculate.result;
}