swift 独有的属性监听方法:
func observe<Value>(_ keyPath: KeyPath<Key, Value>, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (KEY, NSKeyValueObservedChange<Value>) -> Void) -> NSKeyValueObservation
我们在使用时需要单独维护一个NSKeyValueObservation,并且被监听的属性需要增加@objc dynamic 的修饰
var observation: NSKeyValueObservation?
@objc dynamic var name = ""
很多文章说不需要再removeObserver 了,这种说法是不对的,经过测试得知,当监听一个属性时:
observation = self.observe(\.name, options: [.new, .initial]) { (vc, change) in }
在iOS11 及其以上确实是不需要removeObserver的,但是在iOS11 以下,需要在deinit 中移除监听:
deinit {
if let ob = observation {
self.removeObserver(ob, forKeyPath: #keyPath(name))
}
}
// 或
deinit {
observation = nil
}
否则会崩溃错误:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x7fd89760e2b0 of class XXX was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x600000220fa0> (
<NSKeyValueObservance 0x60000004c510: Observer: 0x60000004c4b0, Key path: name, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x60000004c4e0>
)