本地化的字符串比较

sri*_*evi 5 cocoa cocoa-touch objective-c nsstring ios

NSString's localizedCaseInsensitiveCompare:localizedStandardCompare:方法有什么区别?

我阅读了参考资料,但没有弄清楚要使用哪一个.

NSG*_*God 10

localizedCaseInsensitiveCompare: 相当于:

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

localizedStandardCompare: 基本上相当于:

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

因此,主要区别在于如何比较字符串中的数字.

比较以下3个字符串localizedCaseInsensitiveCompare:将导致以下顺序:

"Foo2.txt",
"Foo25.txt",
"Foo7.txt"
Run Code Online (Sandbox Code Playgroud)

另一方面,使用它们进行比较localizedStandardCompare:会产生以下顺序:

"Foo2.txt",
"Foo7.txt",
"Foo25.txt"
Run Code Online (Sandbox Code Playgroud)

虽然这种localizedCaseInsensitiveCompare:方法已经存在,但localizedStandardCompare:最近才添加(OS X 10.6).Finder使用数值方法对文件名进行排序,在添加之前localizedStandardCompare:,开发人员没有简单的方法来确保他们可以像Finder那样对字符串进行排序.

在确定使用哪一个时,如果您要比较的字符串代表文件名,那么您肯定倾向于使用localizedStandardCompare:.