Tuesday, August 3, 2010

Objective-C Event Handling Overview

Objective-C manages user input event as responder chain. It goes backward up from the first responder (object that user is interacting with) until application delegate at the top most.



UIResponder contains methods to catch events. When we create a view as subclass of UIView, it inherits methods to access the events.



We can handle the events by implementing those methods. Following MVC pattern, usually we will delegate it to a controller.

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[controller doSomething];
}

UIControl Target Action Events

When we work with events, the UIResponder class holds many of the methods critical for event control. Similarly, we can access a lot of the methods important to SDK controls through the UIControl class. UIControl is a child of UIView (and thus UIResponder).

The UIControl object introduces a whole new event-handling infrastructure that takes touch events and (eventually) converts them into simple actions, without having to worry about the specifics of how a user accessed control.



When a touch event arrives at a UIControl object (via normal dispatching along the responder chain), the control does something unique. Inside the standard UIResponder methods (such as touchesBegan:withEvent:), a UIControl object turns standard touch events into special control events. These control events broadly describe how the user has interacted with the controls rather than just recording gestures. For example, they might report that a button has been pushed or a slider moved.

Once a standard event has been turned into a control event, a sequence of additional methods is called. First, the UIControl object calls sendActionsForControlEvents:. That in turn breaks down the events it’s been sent and calls sendAction:to:forEvent:, once per event. Here the control event is turned into an action, which is a specific method that’s going to be run in a specific target object. Finally the UIApplication method sendAction:to:fromSender:forEvent: is called by the control, again once per event.

That whole process can be slightly exhausting, and fortunately we shouldn’t normally need to know its details. For our purposes, we should be aware that a UIControl object turns a touch event first into a control event and then into an action with a specific recipient. Even better, it’s only the last part of that conversion, from control event into targeted action, which we need to code.

Summary

Events are catched by the view (UIView) and then, following MVC pattern, they are delegated to the controller to be handled.
 

©2009 Stay the Same | by TNB