Strings are compared for equality using
== 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
(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
To order two strings alphabetically, use
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
BOOL result = [firstString isEqualToString:secondString];
To compare with the empty string (
@""), better use
BOOL result = string.length == 0;