Comparing strings Objective-C
This is just a quick debugging tip: sometimes for no reason string comparison in Objective-C won’t work:) You are sure myString cannot be @”this and that”, but then comparing the 2 strings results succeeds. And here is your code which looks perfect, but still says myString equals to @”this and that” :
if ([myString compare:@"TEST"]==NSOrderedSame) |
Well check if myString is nil, then actually the condition in the if is true. In Objective-C you can send messages to nil objects, calling “compare” on a nil object will return 0 (zero) when compared to NSOrderedSame (which, haha, is as well the number 0), so this is how you end up with the result that actually a nil string is equal to any string you compare it. Keep that in mind.
ALWAYS when you compare a constant and an NSString put the constant first like this- saves a lot of debugging time:
if ([@"TEST" compare:myString]==NSOrderedSame) |
This is absolutely the same condition, but this time you send the “compare” message to an instance of NSString containing the text “TEST” and then you compare to a nil object – wooop, they are not the same. In short- for correct results make sure you are not sending messages to nil objects.
So, a short discussion, but I hope it’s been helpful to understand why the problem happens and how to avoid it.
The post was originally published on the following URL: http://www.touch-code-magazine.com/comparing-strings-objective-c/
·



[...] This post was mentioned on Twitter by Marin Todorov. Marin Todorov said: #touchcodemagazine Comparing strings Objective-C http://goo.gl/fb/INo59 [...]
Thank you this helped a lot!
Gabriel thanks for leaving a comment
This one is really a bummer – caught me few times already
You should just write
if ([myString isEqualToString:@"TEST"])
This is a good tip, Thank you.