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

  • 相关阅读:
    森林 BZOJ 3123
    calc BZOJ 2655
    修路 BZOJ 4774
    无聊的计算器【数论多合一】
    矩阵乘法 BZOJ 2738
    K大数查询 BZOJ 3110
    发展城市 BZOJ 3700
    降雨量 BZOJ 1067
    chrome中showModalDialog解决方案
    MFC webbrowser读取文档的meta分析
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4999478.html
Copyright © 2011-2022 走看看