将发件人作为 id 或特定类转换为 IBAction

Casting sender to IBAction as id or specific class(将发件人作为 id 或特定类转换为 IBAction)
本文介绍了将发件人作为 id 或特定类转换为 IBAction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了两种在 IBAction 语句中处理发送者对象的方法.第一个看起来像这样:

I see two approaches to handling sender objects in IBAction statements. The first looks like this:

-(IBAction)buttonPressed:(id)sender{
 UIButton*someButton=(UIButton*)sender;
 //do something with someButton.tag or whatever
 }

另一个似乎更容易:

 -(IBAction)buttonPressed:(UIButton*)sender{
  //do something with sender.tag or whatever
  }

我通常选择版本 2.如果您知道只有一个按钮会发送到此方法,那么有什么特别的理由更喜欢一种样式而不是另一种吗?

I generally opt for version 2. Any particular reason to prefer one style over the other, if you know that only a button will be sending to this method?

如果 anything 可以作为发送者(如按钮、开关或滑块等),我可以看到版本 1 的优势.但如果您正在寻找 UIButtontag 之类的属性,如果您的发件人不是 UIButton,则不会有太大区别.所以第 2 版似乎要简单得多.

I can see where version 1 is good if anything can be a sender, like a button, or switch or slider, etc. But if you are looking for UIButton properties like tag it won't make much difference if your sender is not a UIButton. So version 2 seems a lot more straightforward.

我只是想看看我是否缺少更喜欢版本 1 的明显理由.

Just thought I'd see if I'm missing an obvious reason to prefer version 1.

推荐答案

我认为使用第二个版本没有问题.我通常使用第二个版本,如果发件人可能不止一种类型的对象,则只使用第一个版本.然后,如果该方法需要知道什么类型的对象,该方法可以在将发送者转换为特定类型之前查询发送者.

I see no problem using the second version. I usually use the second version, only using the first version if the sender may be more than one type of object. Then, if the method needs to know what type of object, the method can query the sender before casting the sender to a particular type.

更频繁地我发现不需要访问发件人,所以我只使用:

Even more frequently I find no need to access the sender, so I just use:

- (IBAction)buttonPressed {
  // Do something.
} 

这篇关于将发件人作为 id 或特定类转换为 IBAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Get an event when UIBarButtonItem menu is displayed(显示UIBarButtonItem菜单时获取事件)