JAHelia
JAHelia

Reputation: 7932

reaching the 'tag' property of sender object

I have created an IBAction like this: -(IBAction) buttonTapped:(id)sender; and connected it to a UIButton using interface builder, the problem is that I can't do something like NSLog(@"%d",sender.tag); the compiler gives me syntax error that the tag property does not exist in object of type id ... but however when I do something like NSLog(@"%@", sender); the console displays info about the button and its tag ... so the question is: how can I reach the tag property of the UIButton through the sender object ?

Upvotes: 1

Views: 665

Answers (3)

jrturton
jrturton

Reputation: 119242

Instead of casting, it often makes for cleaner code just to be more specific in your action declaration:

 -(IBAction) buttonTapped:(UIButton*)sender;

You can use UIButton, UIControl, UIView or whatever level of specificity you require.

Upvotes: 2

Coolant
Coolant

Reputation: 448

You have to cast it, because the compiler does not know the type of object (hence the id type), but the runtime will know.

So, it's similar to :

NSLog(@"%d", [(UIButton*)sender tag]);

Upvotes: 2

Alex Reynolds
Alex Reynolds

Reputation: 96947

Have you tried casting sender? For example:

NSLog(@"%d", ((UIButton *)sender).tag);

Upvotes: 4

Related Questions