Objective-c – “First Responder” – Did I get that right

cocoafirst-respondernibobjective c

Let me summarize this shortly: A "First Responder" in a nib file is an object, which represents the UI control element that has the user's focus. So if the user clicks on a control, the nib sets that clicked UI control as First Responder. In my app I could make an outlet to that "First Responder" from the nib, so that I could for example send a message "make red font color" to whatever the user has activated by clicking.

And then, if this First Responder UI control does not understand that message, the message gets passed up in the responder chain, until a parent element or grandparent (and so on) UI control element understands the message. Otherwise it will be ignored.

So First Responder always establishes a "link" to the UI control that has focus. Is that right?

Best Answer

Right overall picture, wrong implementation details in the first paragraph.

A "First Responder" in a NibFile is an Object …

No, actually, First Responder is nil. Connecting a UI control (e.g., button) to First Responder in a nib is equivalent to [control setTarget:nil] in code.

The reason for the First Responder fake-object in the nib window is that, in IB, you set target and action at the same time (ctrl-drag to target, choose action from pop-up menu). You can't set the action and leave the target unset, like you can in code, so to set it to nil, you need to do so explicitly. That's what First Responder is for: it's a fake object representing nil, so you can set the target and action the same way you would do when setting it to a specific real target.

Of course, you can't use this to set anything else to nil, only views' targets. You can only use it to mean First Responder, not anything else.

So if the user klicks on an UI control, the Nib sets …

The nib doesn't do anything. It's just a freeze-dried collection of objects stored on disk. Even when you instantiate NSNib, all you're doing is defrosting some objects. It's the objects that do things.

In the case at hand, when you unarchive the control you connected to First Responder from the nib, its target is set to nil (remember, that's what First Responder really is: a target of nil). When a control's target is nil, and the user clicks on it, it sends its action to whichever responder is the first responder at the time.

Your second and third paragraphs are correct.

Related Topic