0

Possible Duplicate:
Objective C: what is a “(id) sender”?

I have some questions about the following:

- (IBAction)leftButtonPressed:(id)sender 
{
     UIButton *button = (UIButton*)sender;
     _label.text = button.titleLabel.text;
}

What exactly does (UIButton)*sender do? I mean especially the (UIButton*) with the *. Is it something similar to UIButton *myButton ?

As far as I understand is it some kind of pointer to the button which was pressed, but why is that? And why couldn't I just write

_label.text = sender.titleLabel.text;

since it "is" the button? And how do I know what can be send anyway? I mean could I write something like:

-(void)leftButtonPressed:(color)sender {...}

in order to pass the color of the button?

Community
  • 1
  • 1
Linus
  • 4,643
  • 8
  • 49
  • 74

3 Answers3

2

(UIButton *)sender this is typecasting your id sender to UIButton.

Yes you can write -(void)leftButtonPressed:(color)sender {...} But color should be a valid Class Type and it should be pointer like -(void)leftButtonPressed:(NSColor *)sender {...}

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
1

sometimes you get warning like "incompatible pointer type ...." or "incompatible conversion.." etc... these happens due to error in type casting.. (id) is such kind of type caster who can handle typecasting (here on button action)... i hope you are getting my point.

Vineet Singh
  • 4,009
  • 1
  • 28
  • 39
1

you can not write

_label.text = sender.titleLabel.text;

because sender is of type id, and id object dont have any proerty as titleLabel, so you have to first type cast sender so the compiler knows that is a UIButton type of object which has property named titleLabel.

now if you want to directly use sender then you have to make sure that the method gets fired only on button click event and then change your method as follow

- (IBAction)leftButtonPressed:(UIButton *)sender 

then you can directly use

    _label.text = sender.titleLabel.text;
Vishal Singh
  • 4,400
  • 4
  • 27
  • 43