-1

Possible Duplicate:
Understanding NSString comparison in Objective-C

Code

NSString *nodeType = [subNodeDict objectForKey:@"nodeType"];
NSLog (@"nodeType = %@", nodeType);
NSLog (@"(nodeType == @\"Collection\") = %d", nodeType == @"Collection");
NSLog (@"[nodeType class] = %@ and [@\"Collection\" class] = %@", [nodeType class], [@"Collection" class]);

Log

2013-01-01 04:06:37.895 GoogleClient[4752:c07] <strong>nodeType = Collection
2013-01-01 04:06:37.896 GoogleClient[4752:c07] <strong>(nodeType == @"Collection") = 0
2013-01-01 04:06:37.896 GoogleClient[4752:c07] 

<strong>[nodeType class] = __NSCFString and [@"Collection" class] = __NSCFConstantString

subNodeDict is a JSON response object coming back from the server via AFNetworking.

I can't figure out how to accurately compare a string coming back from the server to a constant string. All non-string objects within subNodeDict work fine. Is there some type of UTF-8 encoding that I need to be using? How can I get the true value nodeType?

Community
  • 1
  • 1
Corky
  • 53
  • 5
  • [So](http://stackoverflow.com/questions/8625936/why-is-this-code-not-recognising-the-nsstring-as-being-equal) [many](http://stackoverflow.com/questions/9154288/why-does-nsstring-sometimes-work-with-the-equal-sign) [duplicates](http://stackoverflow.com/questions/13082427/equal-strings-not-equal). – Kurt Revis Jan 01 '13 at 09:54

2 Answers2

1

== is comparing two pointers, not the content of the strings. To compare NSString use isEqualToString: method.

[nodeType isEqualToString:@"Collection"]

Consider this:

NSString *foo = @"abc";
NSString *bar = @"abc";

foo == bar; // false
[foo isEqualToString:bar]; // true

foo == bar is false because they are different pointers, even though their contents are same.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
0

You shouldn't use == for strings since this is a pointer comparison instaed do something like:

[nodeType compare:@"Collection"]

where compare is a method in NSString

CubeSchrauber
  • 1,199
  • 8
  • 9