Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
From the author of A Façade of Respectability

A Façade of Respectability

The dynamic nature of Objective-C makes proxies very common. If you send a message to an object that doesn't have a corresponding method, then the object gets a chance to forward it. There are two common mechanisms for doing that. The simplest is the -forwardingTargetForSelector: method. This takes the selector as an argument and returns a new receiver. The message will then be sent to that object instead.

You can use this to provide wrappers around objects. The NSControl hierarchy in Cocoa is a good example of this. AppKit provides a set of classes that are all subclasses of NSCell, which implement simple drawing and event handling. They are very lightweight and don't exist in the view hierarchy; they must be embedded in a view to be used. Complex view classes such as NSTableView reuse a single cell instance to draw all of the rows in a single column. When you want to use a single cell, you use an NSControl subclass.

Something like NSButton is a simple NSControl subclass that wraps an NSButtonCell. The cell handles all of the drawing and sending events to the delegate, while the control handles the graphics context and delivers click events to the button.

If you want to implement something a little bit more complicated, then you also need to provide a -forwardInvocation: implementation. This gives you a chance to modify the arguments of the message before passing it to the wrapped object.

  • + Share This
  • 🔖 Save To Your Account