A nil-targeted action is a target–action pair in which the target is nil. There is no designated target object, so the following rule is used: starting with the hit-test view (the view with which the user is interacting), Cocoa looks up the responder chain for an object that can respond to the action message.
Suppose, for example, that we were to configure a button in code, like this:
[self.button addTarget:nil action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
That’s a nil-targeted action. So what happens when the user taps the button? First, Cocoa looks in the UIButton itself to see whether it responds to buttonPressed:. If not, it looks in the UIView that is its superview. And so on, up the responder chain. If a responder is found that handles buttonPressed:, the action message is sent to that object; otherwise, the message goes unhandled (with no penalty).
Thus, in the app we posited earlier, where self is the view controller that owns the view that contains the button, and where the class of this view controller does in fact implement buttonPressed:, tapping the button will cause buttonPressed: to be called!
To create a nil-targeted action in a nib, you form a connection to the First Responder proxy object (in the dock). This is what the First Responder proxy object is for! The First Responder isn’t a real object with a known class, so before you can connect an action to it, you have to define the action message within the First Responder proxy object, like this:
- Select the First Responder proxy in the nib, and switch to the Attributes inspector.
- You’ll see a table (probably empty) of user-defined nil-targeted First Responder actions. Click the Plus button and give the new action a signature; it must take a single parameter (so that its name will end with a colon).
- Now you can Control-drag from a control, such as a UIButton, to the First Responder proxy to specify a nil-targeted action with the signature you specified.