对swift - NSKeyValueObservation的正确理解

swift 独有的属性监听方法:

func observe(_ keyPath: KeyPath, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (KEY, NSKeyValueObservedChange) -> 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: (
Context: 0x0, Property: 0x60000004c4e0>
)

你可能感兴趣的:(对swift - NSKeyValueObservation的正确理解)