tags:

views:

164

answers:

2

I would like to change this code so that if the textName.text contains the word "Blue" it will say @"Wrong color"

This code implies only that if the word has no letters it will say "Wrong color". How can I change it to a specific word (blue) instead of "length] == 0)"?

if([textName.text length] == 0)
{
 text = @"Wrong color";
}

Thank you very much!

+2  A: 
if([textName.text isEqualToString:@"blue"]) {
        text = @"Wrong color";
}
Ed Marty
@"Blue" ? perhaps, as Erik uses both 'blue' and 'Blue' in his post, using caseInsenstiveCompare would be good.
akf
Thanks! Both replies worked great.
+5  A: 

You want to look at string comparison methods on the NSString class. The simplest example is to use isEqualToString:, as such:

if([textName.text isEqualToString:@"blue"]) {
    text = @"Wrong color";
}

However, that can be somewhat limiting, as you're looking specifically if the word is "blue", all in lowercase. If you want to accept different combinations of cases (so that, for example, "blue", "Blue", and "BLUE" all cause "Wrong color"), then you want to use caseInsensitiveCompare:, like this:

if([textName.text caseInsensitiveCompare:@"blue"] == NSOrderedSame) {
    text = @"Wrong color";
}

The big difference is that isEqualToString: will return a boolean value, so you can test it directly inside your if, but caseInsensitiveCompare: returns an NSComparisonResult, so you have to check if it's NSOrderedSame rather than testing the return value itself.

For more info:

Tim
Wow, thanks a lot. That worked perfectly! I really appreciate the help as my question probably was pretty stupid.
You could also lowercase textName.text and still use isEqualToString if thats easier
micmcg