Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison for localization

What is the difference between NSString's localizedCaseInsensitiveCompare: and localizedStandardCompare: methods?

I read the reference but did not get a proper idea of which one to use.

like image 270
sridevi Avatar asked Mar 15 '13 15:03

sridevi


1 Answers

localizedCaseInsensitiveCompare: is equivalent to:

[aString compare:otherString
         options:NSCaseInsensitiveSearch
         range:NSMakeRange(0,aString.length)
        locale:[NSLocale currentLocale]];

localizedStandardCompare: is basically equivalent to:

[aString compare:otherString
         options:NSCaseInsensitiveSearch | NSNumericSearch
         range:NSMakeRange(0,aString.length)
        locale:[NSLocale currentLocale]];

So, the primary difference is in how numbers within strings are compared.

Comparing the following 3 strings using localizedCaseInsensitiveCompare: would result in the following order:

"Foo2.txt",
"Foo25.txt",
"Foo7.txt"

On the other hand, comparing them using localizedStandardCompare: would result in the following order:

"Foo2.txt",
"Foo7.txt",
"Foo25.txt"

While the localizedCaseInsensitiveCompare: method has been around forever, the localizedStandardCompare: was only added recently (OS X 10.6). The Finder sorts filenames using the numeric method, and prior to the addition of localizedStandardCompare:, developers were without an easy way to assure they could sort strings like the Finder did.

When determining which one to use, if the strings you're comparing represent filenames, then you should definitely tend toward using localizedStandardCompare:.

like image 121
NSGod Avatar answered Nov 16 '22 20:11

NSGod