目的模仿Masonry连续运用点语法的操作[self.view mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(@10).offset(1); }];写出一个连加的操作 make.add(10).add(10);想看结果的请直接跳到“最终结果”分析一.定义SQMath类SQMath.h#import <Foundation/Foundation.h>@interface SQMath : NSObject- (NSInteger)result;- (void)add:(int)number;@endSQMath.m#import “SQMath.h”@interface SQMath ()@property (nonatomic, assign) NSInteger number;@end@implementation SQMath- (NSInteger)result { return self.number;}- (void)add:(int)number { self.number += number;}@end使用这个SQMath的add方法 SQMath *math = [[SQMath alloc] init]; [math add:10]; [math add:20]; NSLog(@"%ld", [math result]);二.将函数调用改为点语法如果要用点语法,需要让-add从一个方法变成一个add的属性。但是这样就没有办法传参了- (NSInteger)add;但是如果返回值是一个 NSInteger (^)(NSInteger) 类型的block就可以了。math.add返回的是这个block,这个block是需要一个NSInteger为参数(加数),返回值是NSInteger(结果)。SQMath.m- (NSInteger (^)(NSInteger count))add { __weak typeof(self) weakSelf=self; NSInteger (^addBlock)(NSInteger) = ^(NSInteger addCount){ __strong typeof(weakSelf) strongSelf = weakSelf; strongSelf.number += addCount; return strongSelf.number; }; return addBlock;}或者- (NSInteger (^)(NSInteger count))add { __weak typeof(self) weakSelf=self; return ^(NSInteger addCount) { __strong typeof(weakSelf) strongSelf = weakSelf; strongSelf.number += addCount; return strongSelf.number; };}使用这个SQMath的add方法 SQMath math = [[SQMath alloc] init]; NSLog(@"%ld", math.add(10)); NSLog(@"%ld", math.add(20)); NSLog(@"%ld", math.add(30));三.连续使用点语法只要将Block的返回值更改为self。这样每次add返回的则变成了SQMath的实例对象,这样就可以实现连续点语法的效果了。- (SQMath (^)(NSInteger count))add { __weak typeof(self) weakSelf=self; return ^(NSInteger addCount) { __strong typeof(weakSelf) strongSelf = weakSelf; strongSelf.number += addCount; return self; };}使用这个SQMath的add方法SQMath *math = [[SQMath alloc] init];NSLog(@"%ld", math.add(10).add(20).add(30).result) ;四.将这个改为NSNumber的CategoryNSNumber+SQMath.h#import <Foundation/Foundation.h>#import “SQMath.h”@interface NSNumber (Math)- (NSInteger)sq_add:(void(^)(SQMath *make))block;@endNSNumber+SQMath.m#import “NSNumber+SQMath.h”@implementation NSNumber (SQMath)- (NSInteger)sq_add:(void(^)(SQMath *))block { SQMath *math = [[SQMath alloc] init]; block(math); return math.result;}@endNSNumber+SQMath 使用 NSInteger result = [@10 sq_add:^(SQMath * make) { make.add(10).add(20); }]; NSLog(@"%ld", result);最终结果SQChainProgrammingps:链式编程什么时候用我还真不太清楚,但我知道面试的时候肯定有用 哈哈。