-3

I'm new to objective C (and C) and got baffled over this comparison tonight.

The code is located in a fast enumeration loop, the variables being n and w.

The broken code piece was

if (n == w)

And fixing it was

if ([n isEqualToString:w])

I completely understand why the second works, as I was in fact comparing two strings, and that would be the logical method to use (Just took me a while to find it!) However, I don't understand why the first '==' comparison doesn't work, can anyone explain this in a little detail for me as I can't find any good references exactly how it works.

Many Thanks,

user32045
  • 3
  • 5

3 Answers3

1

== compares the pointers (the addresses to your strings) isEqualToString compares the CONTENTS of the strings. So regardless of whether the strings are the same objects, if they are identical it will return YES.

Lance
  • 8,872
  • 2
  • 36
  • 47
0

the == operator checks for object equality, meaning that the two instances references the same object, whereas the isEqualToString checks for object similarity. To better explain:

NSString* a = [NSString stringWithString:@"a"];
NSString* b = [NSString stringWithString:@"a"];
NSString* c = a;
BOOL equality = a == b; //false
BOOL similarity = [a isEqualToString:b]; //true
equality = a == c; //true

Edit: Thanks for the comment, didn't know that string literals are evaluated to the same instance

Antonio E.
  • 4,381
  • 2
  • 25
  • 35
  • 2
    I actually think a would == b in this case since it they would both point to the same NSConcreteString I believe. – David Zech Apr 10 '14 at 21:56
  • @Nighthawk441 is right, string literals are static, the compiler only builds one string at one address for the string literal @"a" – Lance Apr 10 '14 at 21:56
  • you can change it to `[NSMutableString stringWithString:@"a"]` which force to create new instance – Bryan Chen Apr 10 '14 at 22:02
  • @Lance actually reading this: http://clang.llvm.org/docs/ObjectiveCLiterals.html#caveats explains that there is no guarantee that two equals string literals are evaluated to the same NSConcreteString, it is sure possible but not something you should rely on. – Antonio E. Apr 24 '14 at 09:37
-1

It would be helpful to have more context. Allow me to assume you 'C' code looked something like:

...
char *n = "String A";
char *w = "String B";

if(n == w)
...

In English, the if statement is asking: does 'n' point to the same string as 'w'? In the above case, this would always be false.

More likely, you would like to determine if the string pointed to by 'n' is the same as the string pointed to by 'w'. If so, you might do something like:

if(0 == strcmp(n,w))

The strcmp() function returns zero if the strings pointed to by 'n' and 'w' are the same.