Cocoa Bindings

The Cocoa bindings feature enables you to establish a live connection between an item of data and its presentation in a view. Any change made to the data’s value, either in the view or in the object that stores the data, automatically propagates across the connection.

Using Cocoa bindings reduces the glue code you once had to write to connect a view to its underlying model. Interface Builder, part of Xcode, lets you quickly establish Cocoa bindings.

Art/cocoa_bindings.jpg

The Cocoa bindings feature employs the Model-View-Controller (MVC), Object Modeling, and Mediator design patterns. Specifically, a binding establishes communication between an attribute of a view object and a property of a model object, through a mediating controller object.

Several Technologies Enable Cocoa Bindings

The Cocoa bindings feature relies on several technologies that work together to specify how objects synchronize their values across MVC boundaries:

  • Key-value binding (KVB). This protocol enables a class to establish and remove bindings between objects and to advertise the bindings that it exposes. An object must watch for relevant changes in the object to which it is bound and react to those changes.

  • Key-value coding (KVC). This protocol specifies how you can access a property in an object using the property’s name as the key to the property’s value. You can also use key paths to follow relationships between objects.

  • Key-value observing (KVO). This protocol defines a mechanism through which one object can register with another object to be notified of changes to the value of a specified property.

Controller Objects Help You to Establish Cocoa Bindings

In the Model-View-Controller design pattern, a controller object synchronizes changes in the presentation of data (view layer) with the objects that store that data (model layer), and it communicates changes in stored data to the view that presents the data. In this way a controller object acts as a mediator.

AppKit offers four types of controller objects that you can use unmodified to establish bindings in your app. These controller objects (each of which inherits from the abstract NSController class) are available in the Interface Builder object library:

Technically, you don’t need NSController objects to establish bindings; bindings can be made between any two objects, provided that they’re compliant with KVO and KVC . However, if you don’t use NSController objects, you lose what they offer you, namely, placeholder and current-selection values and the ability to commit and discard pending changes.