String comparison in Objective-C

Objective CNsstring

Objective C Problem Overview


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;

Objective C Solutions


Solution 1 - Objective C

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

Solution 2 - Objective C

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

Solution 3 - Objective C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioningh.amView Question on Stackoverflow
Solution 1 - Objective CjlehrView Answer on Stackoverflow
Solution 2 - Objective CmxgView Answer on Stackoverflow
Solution 3 - Objective CVikram PoteView Answer on Stackoverflow