IOS comparison button name for string

I am just studying the code, so thank you for your patience on this simple question.

Here is my code:

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

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

Many thanks for the help.

+6
string ios objective-c
source share
4 answers

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

 if ([buttonName isEqualToString: @"Button 1"]) { // do something } 
+9
source share

Use the -isEqualToString method:

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

using == , you compare ponters, not the actual values โ€‹โ€‹of the strings they contain

+3
source share

Best way to compare string:

 NSString *string1 = <your string>; NSString *string2 = <your string>; if ([string1 caseInsensitiveCompare:string2] == NSOrderedSame) { //strings are same } else { //strings are not same } 
+1
source share

I found that with Xcode 8.3.1 it is necessary to do:

 if([self.myButton isEqual: @"My text"]) { //do this } 
0
source share

All Articles