views:

296

answers:

2

So, this is pretty straight forward, but I'm not sure how to do it. To get a title from a button, you can use:

NSString *title = [sender titleForState:UIControlStateNormal];

However, is there a way to get other information from the button such as the "Label" or "hint"?

And if there isn't, I want to be able to have different actions if a different button is pressed. So, there is an "add 1" button, an "add 2" button etc, I the same "action" to do slightly different things. This is solved by an "If" statement, but I'm not sure how to do the comparison. (Assuming the button title is "WIN"):

if (title == @"WIN")

Doesn't work, so how can I do the comparison?

(I also tried:

NSString *compare = [[NSString alloc] initWithFormat:@"WIN"];
if (title == compare)
{
do something
}

)

+3  A: 

You should always compare strings using isEqualToString:

if ([title isEqualToString:@"WIN"])

Strings will compare correctly sometimes using the == operator, such as when you compare constant strings, but you shouldn't use == for string comparison in Objective-C (or Java either).

If you compare to strings using ==, then it compares their memory addresses. If you are comparing strings set to some constant, then == will be true. If they are the same string, but different memory addresses, then == will be false.

In a language like Python, == is overloaded, so you get the behavior you "expect."

Andrew Johnson
I would also point out that typically you do not have two buttons which do different things use the same action. Instead, you create two separate actions for the buttons. This way you do not need to check any information about the button (e.g. its title) to figure out what you should be doing.
gerry3
+1  A: 

Another option you can use in a pinch is to set the tag property of the button (in IB or in code) and then check

if (sender.tag == 69) {//one button code} else {other button code}

Kenny Winker