在一些IBAction
我看到:
- (IBAction)pushButton:(id)sender;
这个(id)sender
什么时候用?
在一些IBAction
我看到:
- (IBAction)pushButton:(id)sender;
这个(id)sender
什么时候用?
Matt Galloway(id) sender
在 iPhone Dev SDK 论坛上这样描述了 in actions 的含义:
(id)sender 是将消息发送到该选择器的对象。就像在委托函数中一样,您可以将控制权传递给函数等。
如果您有 2 个对象正在调用该选择器并且您想区分它们,您将使用它。当然,您可以只使用两个不同的函数,但使用一个函数通常更简洁,代码重复更少。
有关更多详细信息,请参阅 UIControl 类参考。
一个例子, UITextField 有一个委托,当 UITextField 编辑结束时触发:
-(IBAction) editingEnded:(id) sender {
// the cast goes here, lets assume there's more than one UITextfield
// in this Owner and you want to know which one of them has triggered
// the "editingEnded" delegate
UITextField *textField= (UITextField*)sender;
if(textField == iAmTheLastTextField)
{
// for example login now.
[self login];
}
}
(id)sender is the object which sent the message to that selector.
代码示例:
- (IBAction)submitButton:(id)sender {
UIButton *button = (UIButton *)sender;
[button setEnabled:NO];
[button setTitle:@"foo" forState:UIControlStateDisabled];
}
“发件人”是变量的名称。
“(id)”表示变量的类型是“id”,代表“任何对象”(如果您愿意,可以将其视为对象层次结构的顶部
该方法的名称是pushButton:并且需要任何类型的 1 个参数。
此方法将链接到 UI 上的按钮。此 UI 的委托将接收此调用,并将引用已进行调用的 UIButton。有时你不需要它,有时你需要访问那个 UIButton 来改变他的属性。
它是Cocoa目标-动作机制的一部分,这是对象可以相互通信的一种方式。为了响应事件(例如鼠标单击),一个对象(通常是某种控件)向另一个对象发送消息。发送者被称为“发送者”,接收者是“目标”,消息是“动作”。
您可以在目标的消息处理程序中使用它来从发送方获取有关操作的其他信息。
我从 Rabskatran 那里学到了东西。但我想更正说“发件人”的唯一部分是变量的名称。它应该是(来自 Apple 文档 - https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html):
“动作消息调用的方法具有特定的签名:单个参数包含对启动动作消息的对象的引用;按照惯例,此参数的名称是 sender。例如,
所以它是一个参数!
这是一个 (id)sender 将标签信息从几个按钮传递到一个 IBAction 的示例。该视频演示了 (id) sender 的概念,我发现它非常有用。