Re: Swift with NSDocument and Revert To... browse all versions.

Bill Pitcher

Quincey Morris
You truly are a Hero! and made an old hacker very happy

thank you
Bill Pitcher

On 24/07/2018, at 6:24 PM, Quincey Morris <quinceymorris@...> wrote:

On Jul 23, 2018, at 23:02 , Quincey Morris <quinceymorris@...> wrote:

Revised version:
Well, dang, I got that wrong. (I “fixed” a typo in the email, forgetting to check that it actually worked.) You can’t use a KeyPath expression like “\WindowController.document.model” in Swift, because “document” has the wrong compile-time type.

An alternative is to use ‘addObserver’ after all and specify a String keypath. Or, you can go ahead an make an extra document property of the correct type, like you did originally. Here’s a slightly cleaner way that can still use the ‘observe’ method:

class WindowController: NSWindowController {
private var documentObservation: NSKeyValueObservation!
@objc dynamic private var windowDocument: Document? {
return document as? Document
@objc static var keyPathsForValuesAffectingWindowDocument: Set<String> {
return ["document"]
override func windowDidLoad() {
documentObservation = self.observe(\WindowController.windowDocument?.model) {
windowController,_ in
if let heldViewController = windowController.contentViewController as? ViewController,
let document = windowController.windowDocument {
heldViewController.documentModel = document.model
heldViewController.documentUpdateChangeCountHandler = document.documentUpdateChangeCountHandler
This derived “windowDocument” property is correctly KVO compliant through its use of the “keyPathsForValuesAffecting<Key>” convenience method. It’s a bit of a mouthful, but it’s easier than doing a manual observation.

Join to automatically receive all group messages.