1

I read that NSObject.observe<Value>() is the new API (introduced in Swift 4) for registering a KVO observer and it supports Swift keypath expression and closure. I wonder what's the approach in the new API to unregister an observer?

The observe<Value>() method returns an NSKeyValueObservation object, which doesn't have a method to cancel the observation explicitly (according to its code it does that implicitly when the object is deallocated by ARC). So it seems the only approach is to use the old NSObject.removeObserver() which uses the old keypath String parameter?

I also find it's hard to find documents for this observe() API. There is no mention of it in NSObject doc (the doc contains description of observeValue() but not this observe<Value>), and code completion in XCode doesn't work with it. The only place I found it was mentioned in Apple official doc is this article Using Key-Value Observing in Swift. That leads me to think if this is incomplete or ongoing work? (But given it was introduced in Swift 4 time frame, I doubt it).

rayx
  • 1,329
  • 10
  • 23

1 Answers1

2

Example of using key-value observing

/// define an Observer
var observation: NSKeyValueObservation?
override func viewDidLoad() {
    super.viewDidLoad()
    /// start observation
    observation = view.observe(\.backgroundColor, options: [.old, .new], changeHandler: { (view, value)  in
    })
    /// invalidate observation
    observation?.invalidate()
    observation = nil
}
Amir Pirzad
  • 121
  • 6
  • 2
    Thanks. I saw `invalidate()` method, but its name was a bit odd to me and the its document contained no description so I ignored it. Now that you said it, I googled this method and found my question was also answered here: https://stackoverflow.com/questions/46591637/in-swift-4-how-do-i-remove-a-block-based-kvo-observer. – rayx Dec 23 '19 at 07:15