The peculiar case of key-value observing function prototype

In this code opened in Xcode window:

observer = AVPlayer(url: url).observe(\.timeControlStatus, options: .new) { player, change in

option click on "observe" shows some minimalistic documentation (keyPath - No description, options - No description). ok - better than nothing. Command click opens some autogenerated swift code which doesn't have "observe" function in it (although there is the relevant "NSKeyValueObservedChange" in that file). Why is this the case and what do I do to view "correct" autogenerated file? It is an iOS target if it matters.

(Interestingly, I also failed to find the reference page for this call on Apple site (e.g. it is not listed here) other than in this overview).

I wonder if there's some magic in Swift to autogenerate this call from another, e.g. this: func observeValue(forKeyPath:of:change:context:)?

1 Like

The observe method has always lacked documentation, and it has always been difficult to even find its declaration.

The problem, I believe, is that the method is not actually defined on NSObject. It's defined on the _KeyValueCodingAndObserving protocol, and Xcode tries to hide the existence of SDK identifiers that start with _.

You can find the implementation of observe as of Swift 5.4 here: NSObject.swift. It was removed from the Swift repo in Swift 5.5, but I doubt the implementation has changed much.

I believe the method is part of a protocol (rather than being defined directly on NSObject) is because that is how you make the Self argument to the closure take on the lexical type of the observed object (in your case, AVPlayer), rather than always being NSObject.

1 Like