106

I've currently got a webserver set up which I communicate over SOAP with my iPhone app. I am returning a NSString containing a GUID and when I attempt to compare this with another NSString I get some strange results.

Why would this not fire? Surely the two strings are a match?

NSString *myString = @"hello world";

if (myString == @"hello world")
    return;
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
ingh.am
  • 25,981
  • 43
  • 130
  • 177
  • http://stackoverflow.com/questions/3703554/understanding-nsstring-comparison Nicely answered here as well. – Emile Feb 19 '14 at 11:37

3 Answers3

251

Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}
jlehr
  • 15,557
  • 5
  • 43
  • 45
  • 2
    AH! Thanking you muchly. Feel like a bit of a fool on this one! – ingh.am Apr 07 '10 at 13:05
  • 4
    My guess is that in ObjectiveC++ you could create an operator overload to give you syntactically-sugary ability to use == but no sane objective C programmer would do this, because == is only used for identity checks in objective C objects. – Warren P Apr 07 '10 at 18:26
54

You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:

if ([category isEqualToString:@"Some String"])
{
   // Both strings are equal without respect to their case.
}

Case-insensitive is like this:

if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
   // Both strings are equal with respect to their case.
}
JJD
  • 50,076
  • 60
  • 203
  • 339
mxg
  • 20,946
  • 12
  • 59
  • 80
  • 1
    I think it should be: ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame) – JaakL Jun 14 '12 at 13:33
  • 11
    Be careful with the "compare" function because if the string (in this case "category") is nil, compare will always return NSOrderedSame. – nh32rg Jul 26 '13 at 15:21
  • That's a great point @nh32rg!! +1 for that! Does the isEqualToString have the same problem? – badweasel Aug 28 '14 at 21:56
5

You can compare string with below functions.

NSString *first = @"abc";
NSString *second = @"abc";
NSString *third = [[NSString alloc] initWithString:@"abc"];
NSLog(@"%d", (second == third))  
NSLog(@"%d", (first == second)); 
NSLog(@"%d", [first isEqualToString:second]); 
NSLog(@"%d", [first isEqualToString:third]); 

Output will be :-
    0
    1
    1
    1
Vikram Pote
  • 5,433
  • 4
  • 33
  • 37