Objective C 链式调用
起因
某日使用DKChainableAnimationKit的时候发现可以如下写代码:
view.animation.rotate(180).anchorTopLeft.thenAfter(1.0).rotate(90).anchorCenter.animanimation无独有偶。Masonry其实也是这样用的
make.right.equalTo(self.view).with.offset(-10);原理
看了一下代码,其实就是通过一个实现了所有方法的Chaining Method Object,每一个方法都返回一个`Block, 这个Block返回类型为Chaining Method Object,Block`的参数为你想要传入的参数类型。
@interface ChainingMethodObject : NSObject- (ChainingMethodObject * (^)(void))doA;- (ChainingMethodObject * (^)(NSInteger i))doB;- (ChainingMethodObject * (^)(NSString* str))doC;- (ChainingMethodObject * (^)(NSString* str, NSArray* array))doD;@end@implementation ChainingMethodObject- (ChainingMethodObject * (^)(NSInteger i))doB{ return ^id(NSInteger i) { //do actual stuff related with B return self; };}...其他方法类似@end通常情况下,ChainingMethodObject都会有delegate存在,具体视实际运用情况而定,如动画库DKChainableAnimationKit中,animation里有个weak var view:UIView指向UIView从而对target View进行操作。
@implementation ChainingMethodObject- (id) initWithObject:(id)obj{ self = [super init]; _delegate = obj; return self;}@end@interface HostObject()ChainingMethodObject * _cObj;@end@implementation HostObject (ChainingMethodObject)- (ChainingMethodObject *) getChainingMethodObject{ if (!_cObj) _cObj = [[ChainingMethodObject alloc] initWithObject:self]; return _cObj;}@end然后就可以了:
HostObject* hostObject = [HostObject new];[hostOjbect getChainingMethodObject].doA.doC(@"Hi there!").doD(@"Hello",@[@1,@2]).doB(100).doA;参考
DKChainableAnimationKit
Masonry

