链式编程思想:下一级的block给上一级使用
思想:把需要做的事情封装到block,给外接提供一个block方法
特点:方法返回值需要是block。block参数:放需要操作的内容,block返回值:方法调用者。都是点语法。
代表:masonry框架
massory:
[view mas_makeConstraints:^(MASConstraintMaker *make){
make.left.top.equalTo(@10);
make.right.bottom.equalTo(@(-10));
}
void(^block)(MASConstraintMaker *make) = ^(MASConstraintMaker *make){
make.left.top.equalTo(@10);
make.right.bottom.equalTo(@(-10));
};
[view mas_makeConstraints:block];
====================
计算器Demo:
#import <Foundation/Foundation.h>
@interface CaculatorMaker : NSObject
@property (assign, nonatomic) int reslut;
- (CaculatorMaker *(^)(int num))add;
- (CaculatorMaker *(^)(int num))multy;
@end
#import "CaculatorMaker.h"
@implementation CaculatorMaker
- (CaculatorMaker *(^)(int num))add
{
return ^(int num){
_reslut += num;
return self;
};
}
- (CaculatorMaker *(^)(int num))multy
{
return ^(int num){
_reslut *= num;
return self;
};
}
@end
#import <Foundation/Foundation.h>
#import "CaculatorMaker.h"
@interface NSObject (Caculator)
//计算机都使用这个方法,一调用这个方法就返回结果
+ (int)makeCaculator:(void(^)(CaculatorMaker *))block;
@end
#import "NSObject+Caculator.h"
@implementation NSObject (Caculator)
+ (int)makeCaculator:(void(^)(CaculatorMaker *))block
{
//创建计算对象
CaculatorMaker *maker = [[CaculatorMaker alloc] init];
//计算
block(maker);
return maker.reslut;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
int result = [NSObject makeCaculator:^(CaculatorMaker *maker) {
//把所有的计算代码封装到这里
maker.add(10).add(20).multy(3);
}];
NSLog(@"%d",result);
}