如何按字母顺序对NSArray进行排序?
问题描述:
如何将按[UIFont familyNames]
填充的数组按字母顺序排序?
How can I sort an array filled with [UIFont familyNames]
into alphabetical order?
答
The simplest approach is, to provide a sort selector (Apple's documentation for details)
Objective-C
sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
快速
let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:")
let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])
Apple提供了几种用于字母排序的选择器:
Apple provides several selectors for alphabetic sorting:
-
compare:
-
caseInsensitiveCompare:
-
localizedCompare:
-
localizedCaseInsensitiveCompare:
-
localizedStandardCompare:
-
compare:
-
caseInsensitiveCompare:
-
localizedCompare:
localizedCaseInsensitiveCompare:
localizedStandardCompare:
快速
var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students.sort()
print(students)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"