美文网首页RxSwift源码解析
DelegateProxy 下篇 Proxy创建

DelegateProxy 下篇 Proxy创建

作者: 狼性刀锋 | 来源:发表于2018-11-10 10:33 被阅读45次

    DelegateProxy 下篇 Proxy创建

    还是从 UIScrollView 的开始,看看Proxy 是怎么创建的。

     extension Reactive where Base: UIScrollView {
     
            public var delegate: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
                return RxScrollViewDelegateProxy.proxy(for: base)
            }
            
     }
     
    

    入口: RxScrollViewDelegateProxy.proxy(for: base)

        public static func proxy(for object: ParentObject) -> Self {
            MainScheduler.ensureExecutingOnScheduler()
    
            let maybeProxy = self.assignedProxy(for: object)
    
            let proxy: AnyObject
            if let existingProxy = maybeProxy {
                proxy = existingProxy
            }
            else {
                proxy = castOrFatalError(self.createProxy(for: object))
                self.assignProxy(proxy, toObject: object)
                assert(self.assignedProxy(for: object) === proxy)
            }
            let currentDelegate = self._currentDelegate(for: object)
            let delegateProxy: Self = castOrFatalError(proxy)
    
            if currentDelegate !== delegateProxy {
                delegateProxy._setForwardToDelegate(currentDelegate, retainDelegate: false)
                assert(delegateProxy._forwardToDelegate() === currentDelegate)
                self._setCurrentDelegate(proxy, to: object)
                assert(self._currentDelegate(for: object) === proxy)
                assert(delegateProxy._forwardToDelegate() === currentDelegate)
            }
    
            return delegateProxy
        }
    
    
    
    

    这段代码分为两个部分

    1. 创建Proxy
    2. 设置 ForwardToDelegate

    create proxy

    
            // 检索是否已存在 Proxy
           let maybeProxy = self.assignedProxy(for: object)
    
            let proxy: AnyObject
            if let existingProxy = maybeProxy {
                proxy = existingProxy
            }
            else { // 如果不存在, 则创建Proxy
                proxy = castOrFatalError(self.createProxy(for: object))
                // 存储 Proxy
                self.assignProxy(proxy, toObject: object)
                assert(self.assignedProxy(for: object) === proxy)
            }
    
    
    

    使用AssociatedObject 存储 Proxy

        fileprivate static func assignedProxy(for object: ParentObject) -> AnyObject? {
            let maybeDelegate = objc_getAssociatedObject(object, self.identifier)
            return castOptionalOrFatalError(maybeDelegate)
        }
    
        fileprivate static func assignProxy(_ proxy: AnyObject, toObject object: ParentObject) {
            objc_setAssociatedObject(object, self.identifier, proxy, .OBJC_ASSOCIATION_RETAIN)
        }
    
    

    这个机制能够确保对于同一个对象 ,多次调用create proxy, 总是返回同一个proxy

    DelegateProxyType identifier

    extension DelegateProxyType {
        /// Unique identifier for delegate
        public static var identifier: UnsafeRawPointer {
            let delegateIdentifier = ObjectIdentifier(Delegate.self)
            let integerIdentifier = Int(bitPattern: delegateIdentifier)
            return UnsafeRawPointer(bitPattern: integerIdentifier)!
        }
    }
    

    可见同一个类型的DelegateProxyType的值UnsafeRawPointer是确定的。

    setForwardToDelegate

            let currentDelegate = self._currentDelegate(for: object)
            let delegateProxy: Self = castOrFatalError(proxy)
    
            // 当前Delegate 不等于 Proxy, 说明用户手动设置了其他代理
            if currentDelegate !== delegateProxy {
                // 将用户手动设置的代理 设置为Forward Delegate
                delegateProxy._setForwardToDelegate(currentDelegate, retainDelegate: false)
                assert(delegateProxy._forwardToDelegate() === currentDelegate)
                self._setCurrentDelegate(proxy, to: object)
                assert(self._currentDelegate(for: object) === proxy)
                assert(delegateProxy._forwardToDelegate() === currentDelegate)
            }
    
    
    
    // 调用proxy 前
    let object: Object
    object.delegate = originalDelegate 
    
    +++++++++++++++++++++++++++++++++++++
    // 调用后
    object.delegate = proxy
    proxy.forwardToDelegate = originalDelegate
    
    然后再通过消息转发机制,将消息转发给originalDelegate, 这样originalDelegate 仍然可以正常工作
    
    
    

    create proxy 具体细节

    extension DelegateProxyType {
        public static func createProxy(for object: AnyObject) -> Self {
            return castOrFatalError(factory.createProxy(for: object))
        }
    
        fileprivate static var factory: DelegateProxyFactory {
            return DelegateProxyFactory.sharedFactory(for: self)
        }
    }
    
    
       private class DelegateProxyFactory {
            private static var _sharedFactories: [UnsafeRawPointer: DelegateProxyFactory] = [:]
    
    
            fileprivate static func sharedFactory<DelegateProxy: DelegateProxyType>(for proxyType: DelegateProxy.Type) -> DelegateProxyFactory {
                MainScheduler.ensureExecutingOnScheduler()
                let identifier = DelegateProxy.identifier
                // 检索_sharedFactories 是否存在相应的DelegateProxyFactory
                // 如果不存在则创建
                if let factory = _sharedFactories[identifier] {
                    return factory
                }
                let factory = DelegateProxyFactory(for: proxyType)
                _sharedFactories[identifier] = factory
                DelegateProxy.registerKnownImplementations()
                return factory
            }
    }
    
    
    1. 通过静态变量存储DelegateProxyFactory, 避免重复的创建,提高运行效率
    2. 按需加载,只有在需要的时候,_sharedFactories 才会添加指定的DelegateProxyFactory
    private class DelegateProxyFactory {
    
            // create factories
            private var _factories: [ObjectIdentifier: ((AnyObject) -> AnyObject)]
            private var _delegateProxyType: Any.Type
    
            //  factory 标识符
            private var _identifier: UnsafeRawPointer
    
            private init<DelegateProxy: DelegateProxyType>(for proxyType: DelegateProxy.Type) {
                _factories = [:]
                _delegateProxyType = proxyType
                _identifier = proxyType.identifier
            }
       }  
            
    

    在创建的过程中,有个非常重要的操作 registerKnownImplementations

    看看它在 RxScrollViewDelegateProxy 的 定义

        // RxScrollViewDelegateProxy Class
        public static func registerKnownImplementations() {
            self.register { RxScrollViewDelegateProxy(scrollView: $0) }
            self.register { RxTableViewDelegateProxy(tableView: $0) }
            self.register { RxCollectionViewDelegateProxy(collectionView: $0) }
            self.register { RxTextViewDelegateProxy(textView: $0) }
        }
    
    
    
    extension DelegateProxyType {
    
        public static func register<Parent>(make: @escaping (Parent) -> Self) {
            self.factory.extend(make: make)
        }
        
    }
    
    
    
        // DelegateProxyFactory Class
            fileprivate func extend<DelegateProxy: DelegateProxyType, ParentObject>(make: @escaping (ParentObject) -> DelegateProxy) {
                    MainScheduler.ensureExecutingOnScheduler()
                    precondition(_identifier == DelegateProxy.identifier, "Delegate proxy has inconsistent identifier")
                    guard _factories[ObjectIdentifier(ParentObject.self)] == nil else {
                        rxFatalError("The factory of \(ParentObject.self) is duplicated. DelegateProxy is not allowed of duplicated base object type.")
                    }
                    _factories[ObjectIdentifier(ParentObject.self)] = { make(castOrFatalError($0)) }
            }
    
    
    

    这里注意registerKnownImplementations、register 都是static 类型, 而extend是 对象方法。 _factories 使用 委托人标识符作为key, 对象proxy创建方法作为value

    从上面代码可以看出来registerKnownImplementations 的作用在于向_factories添加元素(key: 委托对象id, value: factory method) , 上面例子注册完之后 , _sharedFactories 内部属性是看起来是这样的(实际会有些差别,这里忽视了一些细节):

    {
    "RxScrollViewDelegateProxy.id": {
    TableView.id: RxScrollViewDelegateProxy.create method,
    ScrollView.id: RxCollectionViewDelegateProxy.create method,
    CollectionView.id: RxCollectionViewDelegateProxy create method,
    TextView.id: RxTextViewDelegateProxy.create method
    
    }
    
    }
    
    

    createProxy

    
            fileprivate func createProxy(for object: AnyObject) -> AnyObject {
                MainScheduler.ensureExecutingOnScheduler()
                var maybeMirror: Mirror? = Mirror(reflecting: object)
                while let mirror = maybeMirror {
                    if let factory = _factories[ObjectIdentifier(mirror.subjectType)] {
                        return factory(object)
                    }
                    maybeMirror = mirror.superclassMirror
                }
                rxFatalError("DelegateProxy has no factory of \(object). Implement DelegateProxy subclass for \(object) first.")
            }
    
    
    

    利用反射,查找自身以及父类是否被包含在_factories 字典中。并返回匹配的类型。

    简单的 , 说话的方式简单点。 createProxy 分为两个部分

    1. 双层hashmap 的创建
    2. 双层hashmap 的检索

    从创建过程也可以看出 ,传统的工厂模式被 闭包完美替代。
    整个构建过程比较复杂,各种泛化和特化操作,以及范型约束。

    相关文章

      网友评论

        本文标题:DelegateProxy 下篇 Proxy创建

        本文链接:https://www.haomeiwen.com/subject/ybpoxqtx.html