Examples in Cocoa
Compare the MYMediatingController class developed in the "Solution" section of this chapter to Cocoa's NSController and NSArrayController classes documented at http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSArrayController_Class/Reference/Reference.html. The example in the Solution section re-invents the NSArrayController class and reveals both why the NSArrayController class exists and how it can be used in your applications.
NSArrayController mediates between arrays of model objects and your application's view objects; it also keeps track of selection and provides methods to add and remove model objects.
NSTreeController is similar to NSArrayController but enables you add, remove, and manage model objects in a tree data structure. NSTreeController is used with NSOutlineViews.
NSObjectController mediates between a single model object and your application's view objects. NSObjectController is the superclass of NSArrayController and NSTreeController. NSObjectController provides the concept of a single selected object.
NSUserDefaultsController encapsulates reusable code for mediating between user preferences (the User Defaults system) and your application's views.
Controllers and Bindings
Cocoa's NSArrayController class is more or less a drop-in replacement for the developed MYMediatingController class. However, NSArrayController uses a design that even further reduces the amount of application-specific code needed in MYShapeEditor. As shown in Figure 29.5, MYMediatingController posts a notification that's observed by MYShapeEditorDocument so that MYShapeEditorDocument can keep the views synchronized with the model. Cocoa provides a technology called "bindings" that provides an alternative technique for keeping objects synchronized.
Figure 29.5 using
The MYShapeEditor3 folder at www.CocoaDesignPatterns.com implements the MYShapeEditor application with bindings and NSArrayController using the design shown in Figure 29.5. The MYShapeEditorDocument class is simplified in MYShapeEditor3 by removing all of the coordinating code previously used to synchronize views with the model. Bindings configured in Interface Builder replace that functionality.
Bindings are a large enough topic that they deserve their own chapter. Chapter 32, "Bindings and Controllers," describes the Bindings design pattern and its underlying implementation using lower level Cocoa design patterns.