NSString caseInsensitiveCompare confusing ordering

116 views Asked by At

I'm seeing something wired when using NSString caseInsensitiveCompare. For below two strings:

NSString *str1 = @"Výkazy do poisťovní";
NSString *str2 = @"Vyšlé faktúry 2007.xls";

I use NSString caseInsensitiveCompare to compare them,

    int ci1 = [str1 caseInsensitiveCompare:str2];
    int ci2 = [str2 caseInsensitiveCompare:str1];

Since they are different strings, I expect above code should give me 1 and -1. But surprisingly both ci1 and ci2 are 1. How can this happen???

2

There are 2 answers

3
lead_the_zeppelin On

Always use current locale when its a string used for display.

NSString *str1 = @"Výkazy do poisťovní";
NSString *str2 = @"Vyšlé faktúry 2007.xls";

int ci1 = [str1 compare:str2 options:NSCaseInsensitiveSearch range:NSMakeRange(0, str1.length) locale:[NSLocale currentLocale]];
int ci2 = [str2 compare:str1 options:NSCaseInsensitiveSearch range:NSMakeRange(0, str2.length) locale:[NSLocale currentLocale]];
4
matt On

You've found a bug. You can't use simple-minded caseInsensitiveCompare: in this situation. You have to turn off diacritics and case manually, like this:

NSComparisonResult ci1 = [str1 compare:str2 options:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch range:NSMakeRange(0,str1.length)];
NSComparisonResult ci2 = [str2 compare:str1 options:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch range:NSMakeRange(0,str2.length)];