在iOS开发界面布局的库中我们经常使用SDAutoLayout和Masonry,在这我们不讨论如何使用,好奇的是两个框架是如何写出下边的代码,像这种通过”.”的方法将需要执行的代码链接到一起的技巧,成为链式编程。这种方式是我们书写和阅读代码更为容易。个人理解链式编程应该属于一种编程技巧,不属于编程思想。
1 2
| button.sd_layout.leftEqualToView(inView).topSpaceToView(inView, 0).rightEqualToView(inView).heightRatioToView(inView, 1);
|
1 2 3 4
| [view mas_makeConstraints:^(MASConstraintMaker *make) { make.top.bottom.left.right.equalTo(self.view); }];
|
乍一看链式编程好像比较高科技,经过思考我将链式编程通过以下几步进行了分解,方便理解。
声明
1 2 3 4 5 6 7
| @interface ChainingProgram() @property (nonatomic, assign) int total; - (void)calculate; - (ChainingProgram *)add:(int)a; - (void (^)(int))block; - (ChainingProgram *(^)(int))addBlock; @end
|
普通的OC方法
1 2 3
| - (void)calculate { NSLog(@"normal_Calculate"); }
|
调用
返回值为当前类的对象的oc方法
1 2 3 4 5
| - (ChainingProgram *)add:(int)a { NSLog(@"add_%d",a); self.total += a; return self; }
|
调用
这里和链式编程的区别是不是还有一个”[ ]”的距离
1
| [[[[self add:1]add:2]add:3]total];
|
没有返回值的block的实例方法
1 2 3 4 5 6
| - (void (^)(int))block { void (^result) (int) = ^ (int a) { NSLog(@"block_%d",a); }; return result; }
|
调用
block作为属性传递
1 2
| void (^result)(int) = [self block]; result(4);
|
带返回值为当前类对象的block的实例方法
1 2 3 4 5 6 7 8 9
| - (ChainingProgram *(^)(int))addBlock { __weak typeof(self) weakSelf = self; ChainingProgram *(^result)(int) = ^(int a) { NSLog(@"addBlock__%d",a); weakSelf.total += a; return self; }; return result; }
|
也可以缩写为
1 2 3 4 5 6 7 8
| - (ChainingProgram *(^)(int))addBlock { __weak typeof(self) weakSelf = self; return ^(int a){ NSLog(@"addBlock__%d",a); weakSelf.total += a; return self; }; }
|
调用
1
| [self.addBlock(5).addBlock(6).addBlock(7) total];
|
简单说我们熟悉add方法,也熟悉block方法,只要将两者加起来就成为了熟悉又陌生的链式编程方法(addBlock)