oc中kvo的使用大家都比较熟悉了,但是在swift中可能会出现添加了观察者,但是回调方法不走的情况。
class Person: NSObject {
var name: String
override init() {
name = "zhangsan"
}
}
class TestVC : UIViewController{
var person: Person!
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
person = Person()
person.addObserver(self, forKeyPath: "name", options: [.old, .new], context: nil)
person.name = "wangwu"
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
}
deinit {
person.removeObserver(self, forKeyPath: "name")
}
}
在viewDidLoad方法中,监听person对象的name属性变化,按理说没毛病,但是你会发现observeValue回调不会执行。
解决办法:在需要被监听的属性前加上@objc dynamic
class Person: NSObject {
@objc dynamic var name: String
override init() {
name = "zhangsan"
}
}
网友评论