zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    如何让django方法自动地定期执行
    Python的PIL库实现验证码图片
    解决Python2.7的UnicodeEncodeError: 'ascii' codec can’t encode异常错误
    js分页页码算法
    Django站点管理--ModelAdmin
    Django时间查询
    django orm总结
    django Q和F查询
    ubuntu安装redis
    买入股票必须遵循的原则
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4999478.html
Copyright © 2011-2022 走看看