Responder chain and routed events in CocoaTouch

After years of working with C#, .NET, WPF, and Silverlight I find iOS programming to be both wildly foreign and familiar, at the same time. It’s like studying ancient Rome, and understanding the Romans’ pride for their system of law and justice, yet to feel totally alienated by other aspects of their worldview (such as how brutally justice was often doled out). This post discusses the similarity and difference between CocoaTouch’s concept of the Responder Chain, and the WPF/Silverlight concept of Routed Events.

One of the concepts that any WPF or Silverlight programmer worth their salt knows intimately is routed events.

Similarly, any self-respecting iOS developer is well versed in the ways of the responder chain.

Both of these concepts exist, primarily, to process input events in a hierarchical user interface built of elements that can opt to “handle” an input event. In the .NET world, the implementation consists of UI element trees and routed events. In the CocoaTouch world, where MVC is built into the framework, things are a little different. The Controllers that, optionally, drive a View are also given a chance to respond to input events. If a Controller has a parent Controller, the parent gets a shot to handle the event, too. If an event is not handled by any View, Controller, or the Window, the Application singleton object is also given an opportunity.

In the .NET world a control is said to have “focus” when it is the initial target of user input. On the other hand, CocoaTouch has the concept of “first responder”, which is essentially the same thing. For all events other than touch events (such as when the user shakes the iPhone or presses the Pause button on their headset), the first responder in the responder chain gets notified first. If it can’t handle the event, the UIKit will carry the event up the chain notifying other responders, just like a bubbling routed event. For touch events the UIKit framework performs hit-testing to determine which element is the initial responder for the event.

There’s a lot more involved with CocoaTouch’s event infrastructure. If you are interested in learning more about it, start here.

This entry was posted in CocoaTouch. Bookmark the permalink.