views:

33

answers:

2

I have several NSButtons that are attached to a single IBAction. I need to differentiate inside the method between the different buttons. I tried the following, but it doesn't work:

for (int i = 0; i++; i < 7) {
    if (sender == [NSString stringWithFormat:@"button%i", i+1]) 
    {
        NSLog(@"sender is button %i", i+1);
    }
}

How can this be made to work?

+1  A: 

the sender in the btnClicked action is the button object that was clicked. From that you should be able to get the information you need

-(IBAction) btnClicked: (id) sender {
  NSLog(@"Button clicked %@", sender);
  // Do something here with the variable 'sender'
}

If you store a value in the sender.tag, you can determine the button that way also

Aaron Saunders
+2  A: 
-(IBAction)buttonPressed:(id)sender
{
    switch ( [sender tag] )
    {
    case 1:
    //blah blah blah
    break;

    case 2:
    //blah blah etc.
    break;
    }
}

I'm averse to doing the work for you, but....

replace this line

if (sender == [NSString stringWithFormat:@"button%i", i+1]) 

with this line

if ([sender tag] == i) 

Note too that the format of your for loop is invalid:

for (int i = 0; i++; i < 7)

s/b:

for (int i = 0; i < 7; i++)
KevinDTimm
This becomes long if there are lots of buttons, that's why I want to use a for loop to avoid this.
awakeFromNib
@awakeFromNib - something wrong with my edit?
KevinDTimm
I don't understand the part where you say the format is invalid.
awakeFromNib
check the last 3 lines of my answer for the corrected for loop
KevinDTimm