pra*_*ena 42 sorting cocoa-touch objective-c nsmutablearray ios
我有一个字符串列表NSMutableArray,我希望在我的表视图中显示它们之前将它们按字母顺序排序.
我怎样才能做到这一点?
Vij*_*com 128
有下列苹果的工作的例子,使用sortedArrayUsingSelector:和localizedCaseInsensitiveCompare:在集合文档:
sortedArray = [anArray sortedArrayUsingSelector:
@selector(localizedCaseInsensitiveCompare:)];
Run Code Online (Sandbox Code Playgroud)
请注意,这将返回一个新的排序数组.如果你想对你NSMutableArray的位置进行排序,那就sortUsingSelector:改为使用,如下所示:
[mutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Run Code Online (Sandbox Code Playgroud)
这是Swift的更新答案:
在闭包的帮助下,可以在Swift中完成排序.有两种方法- sort并sorted有利于这一点.
var unsortedArray = [ "H", "ello", "Wo", "rl", "d"]
var sortedArray = unsortedArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
Run Code Online (Sandbox Code Playgroud)
注意:这里sorted将返回一个已排序的数组.它unsortedArray本身不会被排序.
如果要对unsortedArray自身进行排序,请使用此选项
unsortedArray.sort { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
Run Code Online (Sandbox Code Playgroud)可选:
localizedCaseInsensitiveCompare也可以这样做,而不是使用:
stringArray.sort{ $0.lowercaseString < $1.lowercaseString }
Run Code Online (Sandbox Code Playgroud)
甚至
stringArray.sort{ $0 < $1 }
Run Code Online (Sandbox Code Playgroud)
如果你想要一个区分大小写的比较
| 归档时间: |
|
| 查看次数: |
36893 次 |
| 最近记录: |