在 IBAction 中拥有 (id)sender 有什么好处
使用 cocoa 编码时,我注意到定义 IBAction
时不需要有 sender
参数,因此以下操作:
- (IBAction)showUserInfo:(id)sender;
可以声明为
- (IBAction)showUserInfo;
所以我想知道是否有除了发送操作的按钮/菜单项之外,还有其他好处吗?我能想到的唯一情况是很少有对象调用相同的 IBAction。还要别的吗?
When coding with cocoa I've noticed that it's not necessary to have sender
parameter when defining IBAction
, hence following action:
- (IBAction)showUserInfo:(id)sender;
can be declared as
- (IBAction)showUserInfo;
So I'm wondering if there is any other benefit besides having the button/menu item that sent the action? Only other situation I can think of is having few objects calling same IBAction. Anything else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Doc 说,
如果您想要从中获取任何数据,sender 参数会有所帮助。例如,在 UISegmentControl 值发生变化时,如@Mark Adams 的回答所示。因此,如果您不需要发件人提供任何信息,则可以省略它,如
- (IBAction)showUserInfo;
示例中所示。Doc says,
The sender parameter helps if you want any data from it. For example, on UISegmentControl value change, as in @Mark Adams answer. So if you don't want any information from the sender, you can just omit it, as in your
- (IBAction)showUserInfo;
example.当您将该方法连接到值可以更改并且您可能需要使用的 UI 对象时,使用
sender
参数会很方便。例如,如果我将一个方法连接到
UISegmentedControl
并将其控制事件设置为 UIControlEventValueChanged,我可以使用作为sender:
参数传递的对象来获取其选定的段索引然后根据该值在 UI 中进行更改。It can be handy to use the
sender
argument when you're connecting the method to UI objects whose values can change and you may need to work with.For instance if I wired up a method to a
UISegmentedControl
and set it's control event to UIControlEventValueChanged, I can use the object passed as thesender:
argument to obtain it's selected segment index and then, based on the value, make a change in the UI.