Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS compare button title to string

I'm just learning how to code so thanks for your patience on this simple question.

Here's my code:

- (IBAction)buttonWasPressed:(id)sender {  
    NSString *buttonName = [sender titleForState:UIControlStateNormal];  
    if (buttonName == @"Button 1") {  
        do something 
    }

How do I compare the title of the button passed as sender to a string?

Much thanks for the help.

like image 396
Trevor McKendrick Avatar asked Mar 11 '11 07:03

Trevor McKendrick


2 Answers

in objective-c you can't compare strings using "==", instead you should use the method isEqualToString from the NSString class to compare a string with another.

if ([buttonName isEqualToString: @"Button 1"]) {
  // do something
}
like image 135
csch Avatar answered Sep 21 '22 11:09

csch


Use -isEqualToString method:

if ([buttonName isEqualToString:@"Button 1"])
   ...

using == you compare ponters, not the actual string values they contain

like image 31
Vladimir Avatar answered Sep 20 '22 11:09

Vladimir