Objective-C Language Comparing Strings


Example

Strings are compared for equality using isEqualToString:

The == operator just tests for object identity and does not compare the logical values of objects, so it can't be used:

NSString *stringOne = @"example";
NSString *stringTwo = [stringOne mutableCopy];

BOOL objectsAreIdentical = (stringOne == stringTwo);          // NO
BOOL stringsAreEqual = [stringOne isEqualToString:stringTwo]; // YES

The expression (stringOne == stringTwo) tests to see if the memory addresses of the two strings are the same, which is usually not what we want.

If the string variables can be nil you have to take care about this case as well:

BOOL equalValues = stringOne == stringTwo || [stringOne isEqualToString:stringTwo];

This condition returns YES when strings have equal values or both are nil.

To order two strings alphabetically, use compare:.

NSComparisonResult result = [firstString compare:secondString];

NSComparisonResult can be:

  • NSOrderedAscending: The first string comes before the second string.
  • NSOrderedSame: The strings are equal.
  • NSOrderedDescending: The second string comes before the first string.

To compare two strings equality, use isEqualToString:.

BOOL result = [firstString isEqualToString:secondString];

To compare with the empty string (@""), better use length.

BOOL result = string.length == 0;