Thursday, September 29, 2011

Regarding first responders: make, don't become

Note: This blog is deprecated. @synthesize zach has moved to a new home, at zpasternack.org. This blog entry can be found on the new blog here. Please update your links.

Things That Were Not Immediately Obvious To Me, #27:

If you have a view which you wish to become first responder, do NOT call becomeFirstResponder on it; it doesn't actually make the view first responder. Instead, call NSWindow's makeFirstResponder:

The NSResponder doc says (emphasis mine):

Use the NSWindow makeFirstResponder: method, not this method, to make an object the first responder. Never invoke this method directly.


This was not immediately obvious to me. Moral of the story: always read the damn docs.

Recapping:

[self becomeFirstResponder]; // Nope, never do that.

[[self window] makeFirstResponder:self]; // That'll do, pig.


As a side note, the description of becomeFirstResponder says:

Notifies the receiver that it’s about to become first responder in its NSWindow.

and

The default implementation returns YES, accepting first responder status. Subclasses can override this method to update state or perform some action such as highlighting the selection, or to return NO, refusing first responder status.


OK, so can someone tell me why this method wasn't named shouldBecomeFirstResponder? Had that been the case, I wouldn't have had to resort to the docs to figure out why it wasn't doing what I thought it should do. Just sayin'.


No comments:

Post a Comment