Cocoa Bindings

I've been trying to understand how to use Cocoa Bindings. There seems to be three ways: key-value observing; Notifications; and Bindings in Interface Builder.

The purpose of bindings is supposedly to avoid writing lots of glue code and make it easy to transfer information between the model, the view and the controller -- but using Notifications and key-value observing seems to involve considerable amounts of code.


Setting bindings in Interface Builder would seem to be the simplest way, though to me the most oblique. Could someone talk me through, or point me to some useful information about how to use this? Essentially, whenever the user triggers an IBAction, it has to do view things and document things. (e.g. get view status info; alter document; reset view)


The View and Window objects only seems to offer Binding to the View Controller. So how do I bind the document to the View?


I've looked at Apple's documentation, and the RayWenderlich site tutorials.


Apart from a lack of code portability, is there really any reason why I shouldn't just define the relevant ViewController in the Document.swift file, and define the relevant Document in the ViewController.swift file, and then just call methods in each one?

Replies

… define the relevant Document in the ViewController.swift file, …


Do you mean you are in the context of document based app ?


Just a hint: did you look at SwiftUI ? As far as I understand, that is one of their purposes to have this "automatic binding", without all the glue.

Yes, MacOS, Swift, document-based app.


I've not used SwiftUI -- would I have to recreate my existing UI?

KVO and notifications are not, in themselves, Cocoa Bindings. I mean, you can think of them as ways of binding the view to the controller and model, but they're not "Bindings".


Bindings is built on top of KVO and KVC. You also don't necessarily need to use IB to establish bindings. You can do it in code, too, using the -bind:toObject:withKeyPath:options: method of NSKeyValueBindingCreation.


You would typically bind the view layer to the controller layer, which would then be bound to the model layer. NSViewController has a representedObject property, which the coordinating controller should set or bind to the relevant part of the model. The coordinating controller would be a document or window controller.

Thanks. But I have to say I find some of Apple's prose to be very oblique. "A Binding is a keypath FOR a property of a receiver, and a keypath is a key path TO a property reachable from a Controller."


OK, let's get more technical. I have a PDFThumbnailView that (when an IBAction is executed) needs to pass its array of .selectedPages to Document.swift, where the related PDFPage object will be rotated, deleted, inserted etc. Then the View needs to be updated.


So is the keyPath the actual property (.selectedPages) in ViewController, and the Binding is just a name for it in Document.swift (which is the receiver)?