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

查看:58
本文介绍了将发件人作为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?

如果任何东西我可以看到版本1的好处可以是发件人,如按钮,开关或滑块等。但如果您正在寻找 UIButton 属性,如标签如果您的发件人不是 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天全站免登陆