开发者

Casting sender to IBAction as id or specific class

开发者 https://www.devze.com 2023-04-02 00:36 出处:网络
I see two approaches to handling sender objects in IBAction statements. The first looks like this: -(IBAction)buttonPressed:(id)sender{

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
 }

Another seems easier:

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

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?

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.

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.
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消