Swift的kvo有两种方式
第一种,直接用oc的kvo,但是需要注意的是
1.class必须继承NSObject
2.属性必须加上@objc dynamic 前缀
3.用后必须在合适的地方调用remove方法
import UIKit
class Person: NSObject {
@objc dynamic var age = 0
}
class ViewController: UIViewController {
let p = Person()
override func viewDidLoad() {
super.viewDidLoad()
p.addObserver(self, forKeyPath: "age", options: [.new, .old], context: nil)
// Do any additional setup after loading the view.
p.age = 30
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "age" {
print(change as Any)
}
}
deinit {
p.removeObserver(self, forKeyPath: "age", context: nil)
}
}
第二种 swift的方式
import UIKit
class Person: NSObject {
@objc dynamic var age = 0
}
class ViewController: UIViewController {
@objc dynamic let p = Person()
var ob: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
self.ob = observe(\.p.age, options: [.new, .old], changeHandler: { (_, change) in
print(change as Any)
})
p.age = 30
}
}
用这种方式的好处就是不用remove观察者
网友评论