I’ve seen one question/answer with a result similar to what I’m looking for, but the code discussed was much more complicated than I have right now.
I’m using a for() loop to create a bunch of a buttons from an array. Then, I have an action, but I’m unable to recognize the button. So:
NSArray *numbers = [NSArray arrayWithOjbects:@"1", "2", "3", nil];
for (int i = 0; i < [numbers count]; i++) {
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(recognize:) forControlEvents:UIControlEventTouchDown];
[button setTitle:[numbers objectAtIndex:i] forState:UIControlStateNormal];
button.frame = CGRectMake(x, y, w, l);
}
Then:
-(void) recognize:(id)sender {
NSLog (button.titleLabel.text);
}
But, I only get the last member of the array (3) regardless of button pressed. I think I’m missing a step in -(void) recognize:(id)sender… that I should be know… but it’s completely escaping me right now.
/Vlad
Each iteration of the loop assigns to the
buttonvariable. When the loop is exited, it will simply hold the last value you assigned to it. Thebuttonvariable appears to be an instance variable – it’s unique to the instance of the class, not to the button.The convenient way of doing what you want is to access the
sendervariable, which iOS supplies to your method. This holds the object that produced the event in question, in this case, the button.Also note that it’s not acceptable to log a text value in that way. If it contains a format string (such as
%@), it will expect a further argument, which it doesn’t get, and will crash. This can be a security hole. When you have a string variable that you want to log, use%@to log it, as above. Xcode should already be warning you about this. Do not ignore warnings.