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;
1

3 Answers 3

255

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...
}
Sign up to request clarification or add additional context in comments.

2 Comments

AH! Thanking you muchly. Feel like a bit of a fool on this one!
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.
55

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.
}

3 Comments

I think it should be: ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
Be careful with the "compare" function because if the string (in this case "category") is nil, compare will always return NSOrderedSame.
That's a great point @nh32rg!! +1 for that! Does the isEqualToString have the same problem?
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.