views:

9

answers:

1

Hi,

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.

+1  A: 

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.

Douwe Maan
Thanks Douwe, too much C# here ;) my C/C++ knowledge was buried under a layer of many years of .NET/Java.
Martín Marconcini
Not a problem ;)
Douwe Maan