I have to implement a small feature in an iPhone app and was wondering if there was a way to do use an if statement where the condition is the string of a button.
Here’s a sample of the code in question:
- (IBAction)someMethod:(id)sender{
UIButton *button = (UIButton *)sender;
if ( button.titleLabel.text == “SomeText” )
{
//do something
}
else
{
// some other thing
}
Now I can’t make it work, because I think I’m using the wrong code in button.titleLabel.text. I’ve even tried @“SomeText”), but I always end up in //some other thing.
What am I doing wrong?
Thanks.
What you’re currently doing is comparing two pointers to objects, the objects
button.titleLabel.textand@"SomeText". As both point to different places in the memory, the comparison will returnNO.If you want to compare the values of both
NSStringobjects, however, you can use[button.titleLabel.text isEqualToString:@"SomeText"].Also note that
"SomeText"is not the same as@"SomeText"! The first is a regular C string, where the last one is a CocoaNSStringobject.