Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How to compare strings (DO NOT use == )

Duncan CDuncan C Posts: 9,114Tutorial Authors, Registered Users @ @ @ @ @ @ @
edited March 2012 in iPhone SDK Tutorials
This topic comes up several times a week on this forum.

First, the bottom line.

Do not use code like this:
if (aString == anotherString)

to compare strings. It won't work. Use
if ([aString isEqualToString: anotherString]) 

instead.

Newbies want to know why the first version won't work.
The answer is that Objective C object variables are actually pointers. The variable aString is a pointer to an NSString object. anotherString is another pointer.

The C == operator compares the address of the two pointer variables. It only evaluates to true if both variables contain the same address. It does not look at the contents of the strings at all.

Instead, NSString has a number of string comparison methods. isEqualToString is the simplest. It checks to see if the two strings contain the same sequence of characters. There are other methods that let you ignore case, diacritical marks, and a number of other options.
Post edited by Duncan C on
Regards,
Duncan C
WareTo

widehead.gif
Animated GIF created with Face Dancer, available for free in the app store.

I'm available for one-on-one help at CodeMentor

Replies

Sign In or Register to comment.