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.
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
}
Use -isEqualToString method:
if ([buttonName isEqualToString:@"Button 1"])
...
using ==
you compare ponters, not the actual string values they contain
The better way to compare string is:
NSString *string1 = <your string>;
NSString *string2 = <your string>;
if ([string1 caseInsensitiveCompare:string2] == NSOrderedSame) {
//strings are same
} else {
//strings are not same
}
I've found that with Xcode 8.3.1, it is necessary to do:
if([self.myButton isEqual: @"My text"]) {
//do this
}
精彩评论