美文网首页
Swift基于PropertyWrapper实现值类型KVO

Swift基于PropertyWrapper实现值类型KVO

作者: 砖头很烫手 | 来源:发表于2020-04-05 15:49 被阅读0次

    背景

    iOS开发对于继承NSObject的类型可以通过原生的observe方法实现属性观察,但在Swift开发时大多数定义的类型并不会继承NSObject,主要包括值类型以及非继承NSObject的class类型,因此这些类型的属性是不具备KVO能力。因此可以思考如何对这些类型的属性进行一层包装来实现KVO能力,同时如何无侵入性的对属性应用这层封装。


    使用方式

    通过PropertyWrapper的方式只要对需要观察的属性加上@Observable标志就具备了KVO能力

    class Person {
        @Observable
        var name: String
        
        init(name: String) {
            self.name = name
        }
    }
    
    struct Car {
        @Observable
        var name: String
    }
    

    然后对于添加了@Observable的属性,通过 $属性名.observe 的方式添加观察回调,然后持有返回值,当返回值被释放时,观察的回调就会被移除。同时还能通过 $属性名.bind 的方式实现属性的绑定(一般用于绑定viewModel数据来UI更新)。

    class ViewController: UIViewController {
        
        let p1 = Person(name: "P1")
        var p2: Person? = Person(name: "P2")
        let car = Car(name: "Car")
        
        var dispose: Disposable?
        let bag = DisposeBag()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            
            view.backgroundColor = .red
            
            dispose = p1.$name.observe { (newValue) in
                print("P1", newValue)
            }
            p1.$name.bind(to: self, at: \ViewController.title).dispose(by: bag)
            p1.$name.bind(to: p2, at: \Person.name).dispose(by: bag)
            p2?.$name.observe { print("P2", $0) }.dispose(by: bag)
            p1.$name.bind(to: car, at: \.name).dispose(by: bag)
            car.$name.observe { print("Car", $0) }.dispose(by: bag)
        }
        
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            p1.name = UUID().uuidString
            p2?[keyPath: \.name] = UUID().uuidString
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                self.p2 = nil
            }
        }
    }
    

    具体实现

    整体功能主要通过Dispose和Observable来实现,下面是核心代码。
    Dispose主要作用是在被释放时在deinit中做清理操作,这里的清理操作主要是移除观察的回调。

    public class Dispose: Disposable {
        
        private let _dispose: () -> Void
        private var hasDisposed = false
        private let lock = NSRecursiveLock()
        
        public init(dispose: @escaping () -> Void) {
            _dispose = dispose
        }
        
        public func dispose() {
            lock.lock {
                if hasDisposed { return }
                hasDisposed = true
                _dispose()
            }
        }
        
        deinit {
            dispose()
        }
    }
    

    Observable主要作用是添加观察者,并且在属性被赋值时触发所有观察者。

    @propertyWrapper
    public class Observable<T> {
        
        public typealias Observer = (T) -> Void
        private typealias Token = UUID
        
        private var value: T
        private var observerMap: [Token: Observer] = [:]
        private let lock = NSRecursiveLock()
        
        public var projectedValue: Observable<T> { return self }
        
        public var wrappedValue: T {
            get {
                return lock.lock { value }
            }
            set {
                lock.lock {
                    value = newValue
                    observerMap.values.forEach{ $0(newValue) }
                }
            }
        }
        
        public init(wrappedValue: T) {
            value = wrappedValue
        }
    }
    
    public extension Observable {
        func observe(_ observer: @escaping Observer) -> Disposable {
            lock.lock(); defer { lock.unlock() }
            let token = Token()
            observerMap[token] = observer
            return Dispose { [weak self] in
                self?.lock.lock(); defer { self?.lock.unlock() }
                // 当Dispose被释放时移除observer
                self?.observerMap[token] = nil
            }
        }
    }
    
    public extension Observable {
        // 值类型KeyPath绑定
        func bind<Target>(to target: Target, at keypath: ReferenceWritableKeyPath<Target, T>) -> Disposable {
            return observe { target[keyPath: keypath] = $0 }
        }
        
        func bind<Target>(to target: Target, at keypath: ReferenceWritableKeyPath<Target, T?>) -> Disposable {
            return observe { target[keyPath: keypath] = $0 }
        }
        
        func bind<Target>(to target: Target?, at keypath: ReferenceWritableKeyPath<Target, T>) -> Disposable {
            return observe { target?[keyPath: keypath] = $0 }
        }
        
        func bind<Target>(to target: Target?, at keypath: ReferenceWritableKeyPath<Target, T?>) -> Disposable {
            return observe { target?[keyPath: keypath] = $0 }
        }
        
        // 引用类型KeyPath绑定
        func bind<Target: AnyObject>(to target: Target, at keypath: ReferenceWritableKeyPath<Target, T>) -> Disposable {
            return observe { [weak target] newValue in
                target?[keyPath: keypath] = newValue
            }
        }
        
        func bind<Target: AnyObject>(to target: Target, at keypath: ReferenceWritableKeyPath<Target, T?>) -> Disposable {
            return observe { [weak target] newValue in
                target?[keyPath: keypath] = newValue
            }
        }
        
        func bind<Target: AnyObject>(to target: Target?, at keypath: ReferenceWritableKeyPath<Target, T>) -> Disposable {
            return observe { [weak target] newValue in
                target?[keyPath: keypath] = newValue
            }
        }
        
        func bind<Target: AnyObject>(to target: Target?, at keypath: ReferenceWritableKeyPath<Target, T?>) -> Disposable {
            return observe { [weak target] newValue in
                target?[keyPath: keypath] = newValue
            }
        }
    }
    

    以Person的name为例,name添加了 @Observable 标记其实是包装成了Observable<String>,而外面调用person.name时,其实调用的是Observable的wrappedValue属性来unwrapper,因此person.name的读写都会触发wrappedValue的get和set方法,因此在set中来触发所有观察者。而person.name和person.$name的区别是person.$name是调用Observable的projectedValue属性,因此这里返回了self(既Observable<String>类型),这时就能调用Observable的方法来添加观察回调。


    以上是这个功能的整体实现思路,轻量级、侵入性低。如有错漏或更好的建议大家可以评论处讨论下。

    内推:字节跳动疯狂招人中,有意者私信一下😝

    相关文章

      网友评论

          本文标题:Swift基于PropertyWrapper实现值类型KVO

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