Search code examples
swiftmacoscocoa-bindings

How to use cocoa bindings with keys in your document subclass?


Here is the definition of my freqstart variable in my Swift app:

enter image description here

This is inside my NSDocument subclass, NECDocument. My NECDocumentVC subclasses NSViewController and has a link to NECDocument, so I can access those vars from the VC:

enter image description here

Note that both objects are part of the NS* class hierarchy, so everything should work fine with KVO.

I am using it this way:

enter image description here

The problem is that the key path is invalid, as you can see from the grey ! in the field. For fun, I placed the same variable in my VC, and presto, the value came up fine. I've tried a bunch of different syntax's in the key path, but nothing I've tried works. Is there something about that document that needs to be different?

I started over - I added an NSObjectController to the storyboard, set its class to NECDocument and it's binding to NECDocumentVC->self.document. Then I bound the text field to point to the OC, and now it auto-completed "freqstart" with no !. The only problem is that now it says "No selection", and it's not clear how I would change the selection, which is read only.

I don't want to put all my variables in my VC, that's simply not where they belong. So can someone suggest a way to solve this?

UPDATE:

I added a Referencing Outlet to my DocumentVC, and then added SettingsController?.addObject(document!) to the viewDidAppear. Now running the app results in:

2016-03-03 14:28:05.880 SwiftNEC[73373:6282035] Cannot update for observer for the key path "document.usegreens" from , most likely because the value for the key "document" has changed without an appropriate KVO notification being sent. Check the KVO-compliance of the SwiftNEC.NECDocumentVC class.

Ok, so is it possible to use a calculated property like my definition of document with KVO?


Solution

  • You are changing the document property of the vc in a non-KVO way. Instead of binding the content of the object controller, do SettingsController?.content = document! in viewDidLoad or viewWillAppear.