Case insensitive comparison NSString
if( [@"Some String" caseInsensitiveCompare:@"some string"] == NSOrderedSame ) {
// strings are equal except for possibly case
}
The documentation is located at Search and Comparison Methods
NSString *stringA;
NSString *stringB;
if (stringA && [stringA caseInsensitiveCompare:stringB] == NSOrderedSame) {
// match
}
Note: stringA &&
is required because when stringA
is nil
:
stringA = nil;
[stringA caseInsensitiveCompare:stringB] // return 0
and so happens NSOrderedSame
is also defined as 0
.
The following example is a typical pitfall:
NSString *rank = [[NSUserDefaults standardUserDefaults] stringForKey:@"Rank"];
if ([rank caseInsensitiveCompare:@"MANAGER"] == NSOrderedSame) {
// what happens if "Rank" is not found in standardUserDefaults
}