将发件人作为 id 或特定类转换为 IBAction [英] Casting sender to IBAction as id or specific class

查看:9
本文介绍了将发件人作为 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆