How do I set and get UIButtons' tag?

You need to cast sender as a UIButton:

-(IBAction)buttonPressed:(id)sender{
UIButton *button = (UIButton *)sender;
NSLog(@"%d", [button tag]);
}

Edit: Regarding the message "unrecognized selector"...

Based on your error message, it's not able to call the buttonPressed method in the first place. Notice in the error message it is looking for "buttonPressed" (no colon at end) but the method is named "buttonPressed:". If you are setting the button target in code, make sure the selector is set to buttonPressed: instead of just buttonPressed. If you are setting the target in IB, the xib may be out of sync with the code.

Also, your original code "[sender tag]" should also work but to access button-specific properties, you'll still need to cast it to UIButton.


I know this is an old question and been answered many a time in other questions, but it came up in a google search as second from the top. So, here is the answer to why it was crashing. Change it to 'button.tag'

-(void)myMethod
{
   UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
   [theButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];

    theButton.tag = i;//or whatever value you want.  In my case it was in a forloop

}

-(void)buttonPressed:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSLog(@"%d", button.tag);
}