Use an If statement with the button name in Objective-C (Cocoa/iPhone SDK)
I have to implement a sma开发者_Go百科ll 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.text
and @"SomeText"
. As both point to different places in the memory, the comparison will return NO
.
If you want to compare the values of both NSString
objects, 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 Cocoa NSString
object.
精彩评论