What is sender?
I can't find this answer anywhe开发者_如何学运维re. What does it mean when there's a sender parameter in a method header? Does it represent the instance that called it, or the method that called it?
What does it mean when there's a sender parameter in a method header? Does it represent the instance that called it, or the method that called it?
Look at the type of the argument. Chances are, it's id
. That's the type of an object pointer. You're correct that it is the instance that sent the message.
You can pass a message selector to a message, but the type for that is SEL
, not id
. Likewise, you can pass a method implementation to a message, but the type for that is IMP
, not id
.
Methods that take a single sender
argument are typically action methods, usually identified by the IBAction
return type. As zoul said, IBAction
expands to void
for the compiler, which tells it that the method does not return a value. The reason to have IBAction
is that Interface Builder looks for methods with IBAction
as the return type and detects them as actions you can wire a control up to.
For more information for Cocoa (Mac OS X), see “The Target-Action Mechanism” in the Cocoa Fundamentals Guide and the Control and Cell Programming Topics for Cocoa.
For more information for Cocoa Touch (iPhone/iPod touch/iPad), see “The Target-Action Mechanism” in the UIControl class reference.
There's no magic involved. You are probably talking about the methods linked to some user interface elements by Interface Builder, right?
- (IBAction) userDidPressButton: (id) sender {...}
The IBAction is a macro that expands to void. It's simply a syntactic sugar that marks the methods you want to be available in the Interface Builder. Now when you connect this method to some interface element, say a button, IB calls the addTarget... method on the button:
[button addTarget:yourObject action:@selector(userDidPressButton:) forEvent:...];
And when you press the button, it goes through its list of actions and fires the userDidPressButton, passing itself as the first argument. This is probably not that much useful for buttons, but you can also use the same mechanism to get change events from a slider, and in that case you can use the sender argument to get the slider value.
Ofcourse there are a lot of technical ways to describe this, But in 'no no' theory the sender argument it passes is just the GUI object that passes it.
So if you link this method to a specific button we will call Button1, the sender is Button1, and with it comes all the information thats available for the button. Size, text etc
hope this was enough.
Bryan
精彩评论