一步一步教你理解和实现iOS中的链式编程和函数式编程

谈到链式编程和函数式编程,那Masonry几乎就是最经典的代表.如:

1
make.top.equalTo(self.view).offset(60)

像这样top.equalTo(self.view).offset(60)通过”点”语法,将需要执行的代码块连续的书写下去,就是链式编程.它能使代码简单易读,书写方便

像这样equalTo(self.view)通过’()’去调用函数,一般调用完返回的还是这个对象本身,就是函数式编程.


1.传统写法,两个方法需要单独调用,也不能任意组合顺序

创建Person类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Person.h:
- (void)eat1;
- (void)sleep1;
Person.m:
- (void)eat1
{
NSLog(@"%s",__FUNCTION__);
}
- (void)sleep1
{
NSLog(@"%s",__FUNCTION__);
}

控制器中调用Person类中方法

1
2
3
4
5
ViewController.m:
Person *person = [[Person alloc] init];
[person eat1];
[person sleep1];

2.用’[]’实现连续调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Person.h:
- (Person *)eat2;
- (Person *)sleep2;
Person.m:
- (Person *)eat2
{
NSLog(@"%s",__FUNCTION__);
return self;
}
- (Person *)sleep2
{
NSLog(@"%s",__FUNCTION__);
return self;
}
ViewController.m:
[[person eat2] sleep2];
[[person sleep2] eat2];

3.用’()”实现函数式编程,用block实现

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
Person.h:
- (void (^)())eat3;
- (void (^)())sleep3;
Person.m:
- (void (^)())eat3
{
//定义block
void (^eat3Block)() = ^ {
NSLog(@"%s",__FUNCTION__);
};
return eatBlock;
}
- (void (^)())sleep3
{
return ^ {
NSLog(@"%s",__FUNCTION__);
};;
}
ViewController.m:
person.eat3();
person.sleep3();

4.实现函数式 + 链式(无参)

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
Person.h:
- (Person * (^)())eat4;
- (Person * (^)())sleep4;
Person.m:
- (Person *(^)())eat4
{
Person * (^eat4Block)() = ^ {
NSLog(@"%s",__FUNCTION__);
return self;
};
return eat4Block;
}
//上下两种写法一样
- (Person *(^)())sleep4
{
return ^ {
NSLog(@"%s",__FUNCTION__);
return self;
};
}
ViewController.m:
person.eat4().sleep4();
person.sleep4().eat4();

5.实现函数式 + 链式(带参)

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
Person.h:
- (Person * (^)(NSString *foodName))eat5;
- (Person * (^)(NSInteger hour))sleep5;
Person.m:
- (Person *(^)(NSString *))eat5
{
Person * (^eat5Block)() = ^(NSString *foodName) {
NSLog(@"吃: %@",foodName);
return self;
};
return eat5Block;
}
//上下两种写法一样
- (Person *(^)(NSInteger))sleep5
{
return ^(NSInteger hour) {
NSLog(@"睡了%ld小时",(long)hour);
return self;
};
}
ViewController.m:
person.eat5(@"蛋糕").sleep5(8);
person.sleep5(8).eat5(@"面包");
Stevin wechat
扫码及时获取更多文章