Hi this is Marin - the author of Touch Code Magazine, I hope you are enjoying my tutorials and articles. Also if you need a bright iPhone developer overseas contact me - I do contract work. Here's my LinkedIn profile

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/

 

  ·

 


Marin Todorov

is an independent iOS developer and publisher. He's got more than 18 years of experience in a dozen of languages and platforms. This is his writing project.
» Contact    » Add Marin on Google+

  1. [...] This post was mentioned on Twitter by Marin Todorov. Marin Todorov said: #touchcodemagazine Comparing strings Objective-C http://goo.gl/fb/INo59 [...]

  2. Gabriel on Monday 12, 2010

    Thank you this helped a lot! :)

  3. Marin on Monday 12, 2010

    Gabriel thanks for leaving a comment :)
    This one is really a bummer – caught me few times already

  4. bob on Monday 12, 2010

    You should just write

    if ([myString isEqualToString:@"TEST"])

  5. Scott Woods on Monday 12, 2010

    This is a good tip, Thank you.