Technical Q&A QA1871

Cocoa Bindings in OS X Storyboards

Q:  Given that there is no File’s Owner in an OS X storyboard, how can I bind the UI elements in my view controller scenes to my application's model objects?

A: In an OS X storyboard, every scene has a controller. We use that controller to manage the content of the scene and interact with the other parts of the application, thus you don’t need a File’s Owner object anymore. (For more information on File’s Owner, see the About File's Owner section of Resource Programming Guide.)

In your view controller scene, the controller is an object of the NSViewController subclass. You can use its representedObject property, or make any number of other properties that are more type-safe, to represent the model your view controller works with, and then bind through them.

For Cocoa bindings to work correctly, be sure that the model properties are ready for use when Cocoa bindings need them. This is especially important when you need to load the model data immediately after the application launch. To achieve that, there are two cases to consider:

Once the model properties have been set up, you can safely use key paths starting with "self.representedObject" (or other properties you defined). Figure 1 shows you how to bind an NSArrayController object within a view controller scene to the managedObjectContext property of the view controller's representedObject (which represents a document object owning that property).

Figure 1  Binding to the view controller's model property

Be aware that the object of a model property may be replaced when it is written back through Cocoa bindings. As an example, when you bind an NSArrayController object to an NSMutableArray property, NSArrayController uses the mutableArrayValueForKey: method defined in NSKeyValueCoding.h to write back changes. Your NSMutableArray object will be replaced with a new array if you don't implement the array mutation methods for the property. The details are covered in NSKeyValueCoding.h.



Document Revision History


DateNotes
2016-04-04

Adjusted the image size and added the content related to the mutability of model properties.

2016-03-31

Adjusted the image size and added the content related to the mutability of model properties.

 

Adjusted the image size and added the content related to the mutability of model properties.

2016-02-18

New document that describes how to bind the UI elements in view controller scenes to an application's model objects.