背景
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, 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 {
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 { 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(to target: Target, at keypath: ReferenceWritableKeyPath) -> Disposable {
return observe { target[keyPath: keypath] = $0 }
}
func bind(to target: Target, at keypath: ReferenceWritableKeyPath) -> Disposable {
return observe { target[keyPath: keypath] = $0 }
}
func bind(to target: Target?, at keypath: ReferenceWritableKeyPath) -> Disposable {
return observe { target?[keyPath: keypath] = $0 }
}
func bind(to target: Target?, at keypath: ReferenceWritableKeyPath) -> Disposable {
return observe { target?[keyPath: keypath] = $0 }
}
// 引用类型KeyPath绑定
func bind(to target: Target, at keypath: ReferenceWritableKeyPath) -> Disposable {
return observe { [weak target] newValue in
target?[keyPath: keypath] = newValue
}
}
func bind(to target: Target, at keypath: ReferenceWritableKeyPath) -> Disposable {
return observe { [weak target] newValue in
target?[keyPath: keypath] = newValue
}
}
func bind(to target: Target?, at keypath: ReferenceWritableKeyPath) -> Disposable {
return observe { [weak target] newValue in
target?[keyPath: keypath] = newValue
}
}
func bind(to target: Target?, at keypath: ReferenceWritableKeyPath) -> Disposable {
return observe { [weak target] newValue in
target?[keyPath: keypath] = newValue
}
}
}
以Person的name为例,name添加了 @Observable 标记其实是包装成了Observable
以上是这个功能的整体实现思路,轻量级、侵入性低。如有错漏或更好的建议大家可以评论处讨论下。
内推:字节跳动疯狂招人中,有意者私信一下