我有一个字符串列表在
我该如何做呢?
NSMutableArray
中,并且我想在将它们显示在我的表视图之前按字母顺序排序它们。我该如何做呢?
NSMutableArray
中,并且我想在将它们显示在我的表视图之前按字母顺序排序它们。以下是苹果官方文档中的示例,使用 sortedArrayUsingSelector:
和 localizedCaseInsensitiveCompare:
在 集合文档 中进行排序:
sortedArray = [anArray sortedArrayUsingSelector:
@selector(localizedCaseInsensitiveCompare:)];
请注意,这将返回一个新的排序数组。如果您想原地排序您的NSMutableArray
,则使用sortUsingSelector:
,像这样:[mutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
以下是有关 Swift 的更新答案:
Sorting can be done in Swift with the help of closures. There are two methods - sort
and sorted
which facilitate this.
var unsortedArray = [ "H", "ello", "Wo", "rl", "d"]
var sortedArray = unsortedArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
Note: Here sorted
will return a sorted array. The unsortedArray
itself will not be sorted.
If you want to sort unsortedArray
itself, use this
unsortedArray.sort { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
可选项:
除了使用localizedCaseInsensitiveCompare
,也可以这样做:
stringArray.sort{ $0.lowercaseString < $1.lowercaseString }
stringArray.sort{ $0 < $1 }
如果你需要进行区分大小写的比较
获取升序很容易。按照以下步骤进行:
模型1:
NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray=[yourArray sortedArrayUsingDescriptors:@[sortDesc]];
如果您希望排序不区分大小写,您需要像这样设置描述符:
模型2:
NSSortDescriptor * sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
sortedArray=[yourArray sortedArrayUsingDescriptors:@[sortDesc]];
对我来说,这个方法可行...
areas = [areas sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
这里是 NSArray
。希望能对某些人有所帮助。
.lowercaseString
对于我使用标题比较对象很有用。mediaItems = mediaItems.sorted { $0.media.title.lowercaseString > $1.media.title.lowercaseString }
- Gerrit Post