objective-c - objective-c : what is a "(id) sender"?

标签 objective-c ibaction sender

在一些IBAction中我看到了:

- (IBAction)pushButton:(id)sender;

这个(id)sender什么时候用?

最佳答案

Matt Galloway 描述了 (id) sender 的含义因此,在 iPhone Dev SDK 论坛上采取行动:

(id)sender is the object which sent the message to that selector. It's like in the delegate functions where you have the control passed in to the function, etc.

You'd use this if you had 2 objects which were calling that selector and you wanted to distinguish between them. Of course, you could just use two different functions, but it's often cleaner and less duplication of code to use one function.

查看 UIControl Class Reference了解更多详情。


一个例子,UITextField 有一个委托(delegate),当 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];
   }
}

关于objective-c - objective-c : what is a "(id) sender"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5578139/

相关文章:

iphone:- MKReverseGeocoder 获取 postalCode、subAdministrativeArea、locality 和 subThoroughfare 的空值

objective-c - 如何将特定混合模式添加到自定义 AccessoryView

objective-c - 在 Objective-C 中自动点击 iTunes 鼠标

android - 从发件人转换时无法在 Remote Media Controller 中显示专辑封面

iphone - MK map View : On startup user location -> zooming

ios - 是否可以将两个按钮链接到同一个 ViewController 中的两个不同的 ibactions?

ios - 在不同的 View Controller 中执行操作

ios - 调用电话操作无法快速工作

objective-c - 获取父菜单中 NSMenuItem(发送者)的索引

swift - 在多个 ImageView 上使用点击手势识别器