Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
From the author of Models and Views

Models and Views

The one design pattern that everyone has heard of is the model-view-controller pattern. View objects provide methods for displaying data and expose some generic interfaces. Model objects represent the data and provide some model-specific interfaces. Controllers join the two together.

AppKit was designed around this idea back when it ran on NeXTSTEP. While this does produce very clean code, most developers found that a disproportionate amount of their time was spent writing controllers. A few releases ago, Apple introduced the NSController hierarchy, which provided a set of generic interfaces and was part of the Cocoa Bindings system.

Bindings use two quite low-level technologies in Objective-C. The first is Key-Value Coding (KVC). This provides a generic way of accessing object properties. When you send an object a -valueForKey: or -setValue:forKey: message, the KVC system checks the object's instance variables and accessor methods, and finally calls a fall-back method to get or set the specified key.

The Key-Value Observing (KVO) mechanism is a bit more complicated. This sends notifications before and after a property is changed. If you set the property with KVC, these notifications are sent automatically; otherwise you must send them manually.

The final addition to the KVC/KVO mechanism that makes bindings possible is the idea of a key path. If you have a supervisor property in an employee object and you want the name property of that object, you can request the “supervisor.name” key path.

With a generic mechanism for accessing and setting properties in objects, there is a lot less of a need for controllers. The generic controllers in the bindings system just need a few key paths to be defined and then they can communicate with the model objects.

A good example of this is NSTreeController, which is used for hierarchical relations between objects. You tell this controller which key to use to get the children of a node and it can navigate a tree of objects. Optionally, you can also provide keys for things like the number of children, which makes things slightly faster.

You won't (yet) find this in the iPhone, but you can implement something similar yourself. The iPhone supports KVC and KVO, so if you make sure that your models are KVC and KVO compliant you can write some generic controllers that implement the UIKit delegate protocols and use KVO/KVC to provide the data.

  • + Share This
  • 🔖 Save To Your Account