Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting sender to IBAction as id or specific class

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.

like image 664
johnbakers Avatar asked Aug 31 '11 12:08

johnbakers


1 Answers

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.
} 
like image 181
Mr. Berna Avatar answered Sep 23 '22 13:09

Mr. Berna