如何对包含字典的数组进行排序?

34

我有一个包含字典的数组,那么如何根据字典中的键值对来对数组进行排序呢?


1
这个问题在Stackoverflow上有提到,链接是https://dev59.com/61PTa4cB1Zd3GeqPk59x#4767282。 - Girish Kolari
5个回答

90
如果数组中的每个元素都是包含某个键的字典,您可以使用排序描述符对数组进行排序。例如,如果每个元素都是包含名为“name”的键的字典:
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name"
    ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];

如何对整数值进行排序? - Shahbaz Akram

13

另一种实现这个功能的方法是使用sortedArrayUsingComparator:方法。

NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [[obj1 valueForKey:@"value"] compare:[obj2 valueForKey:@"value"]];
}];

1
为什么不使用已经具备排序元素属性的有序字典数据结构呢?
请点击这里进行查看。
希望能对您有所帮助。

0

上面Bavarious分享的答案对我很有帮助。只想再补充一点,如果你想对一个可变数组进行排序,请使用以下代码:

NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSMutableArray *sortedArray = [[NSMutableArray sortedArrayUsingDescriptors:sortDescriptors]mutableCopy];

-3
 let arrDescriptor = NSSortDescriptor(key: "order", ascending: true)
 let sortDescriptors: NSArray = [arrDescriptor]
 let sortedArray = instancesubArray.sortedArray(using: sortDescriptors as [AnyObject] as [AnyObject] as! [NSSortDescriptor])

 print(sortedArray)

请使用[编辑]链接来解释这段代码的工作原理,而不仅仅给出代码,因为解释更有可能帮助未来的读者。另请参见[答案]。 - Jed Fox

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接