iOS封装一个链式编程的应用框架

写一个能够实现连加(乘除减类似)

1
2
n.add(10).add(20).add(30);
n = 60;

首先写一个NSObject的分类,便于所有类都可调用:
通过分析Masonry

结构

1
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block;

##我们可以定义此方法为:

1
+ (int)rr_makeConstraints:(void(^)(SumManager *manager))block;

1
2
SumManager就相当于MASConstraintMaker中的约束制造者
在这里担任加法管理者

SumManager.h

1
2
3
4
5
6
7
8
9
10
#import <Foundation/Foundation.h>

@interface SumManager : NSObject

/** */
@property (nonatomic,assign) int result;

- (SumManager * (^)(int value))add;

@end

SumManager.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#import "SumManager.h"

@implementation SumManager

- (SumManager * (^)(int value))add{

return ^(int value){

_result += value;

return self;
//返回一个“方法调用者”
};

}

@end

NSObject+Sum.h

1
2
3
4
5
6
7
#import <Foundation/Foundation.h>
#import "SumManager.h"
@interface NSObject (Sum)

+ (int)rr_makeConstraints:(void(^)(SumManager *manager))block;

@end

NSObject+Sum.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#import "NSObject+Sum.h"

@implementation NSObject (Sum)

+ (int)rr_makeConstraints:(void(^)(SumManager *manager))block{

SumManager *mgr = [[SumManager alloc] init];

block(mgr);

return mgr.result;

}

@end

正式使用:ViewController.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

#import "ViewController.h"
#import "NSObject+Sum.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

int sum = [NSObject rr_makeConstraints:^(SumManager *manager) {

manager.add(10).add(20).add(30);

}];

NSLog(@"sum == %d",sum);


}



- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}


@end

输出结果:

1
2017-06-19 16:44:46.000 002-链式编程思想[3006:1593180] sum == 60