如何按字母顺序对NSArray进行排序?
其他回答中提到了使用@selector(localizedCaseInsensitiveCompare:)
。对于NSString数组来说这很好用,然而如果你想将其扩展到另一种类型的对象,并按照对象的“名称”属性对这些对象进行排序,你应该这样做:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];
你的对象将根据这些对象的名称属性进行排序。
如果你想让排序不区分大小写,你需要像这样设置描述符
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
最简单的方法是提供排序选择器(有关详细信息,请参见苹果的 文档 )
Objective-C
sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Swift
let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:") let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])
苹果为字母表排序提供了几个选择器:
compare:
caseInsensitiveCompare:
localizedCompare:
localizedCaseInsensitiveCompare:
localizedStandardCompare:
Swift
var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] students.sort() print(students) // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"