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 ObjectBlock`的参数为你想要传入的参数类型。

@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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值