如何对包含NSDictionary对象的NSArray进行最佳排序?

69

我正在努力尝试对字典数组进行排序。

我的字典有一些有用的值,如价格、受欢迎程度等。

有什么建议吗?

6个回答

201

可以像这样使用NSSortDescriptor..

NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES];
stories = [stories sortedArrayUsingDescriptors:@[descriptor]];
recent = [stories copy];

stories是您想要排序的数组。 recent是另一个可变数组,其中包含已排序的字典值。将@"interest"更改为您要排序的键值。

祝一切顺利


12
这很好,但是会发生泄漏。1)应该释放或自动释放排序描述符,2)复制调用不必要,可以删除该行。 - Tom Andersen
5
NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES] autorelease]; [stories sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]; - Tom Andersen
2
你可以使用NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"interest" ascending:YES]; - maxcanna
1
recent = [[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]] copy]; 最近 = [[故事 sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]] copy]; - J3RM
你需要在排序调用期间存储输出:NSArray* recent = [stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]; - Rob
显示剩余2条评论

25
[array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
我不想将它分成几行。对我来说,它已经足够简单了。

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; [resultArray1 sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]; - johndpope

11

你只需从父级遍历到所需的子属性。例如:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child"  ascending:YES];

你真是个小明星。这帮助我排序了一个子子字典。非常感谢! - Rambatino
它没有回答问题! - Rambatino

4

更新,sortUsingDescriptors现在已经更名为sortedArrayUsingDescriptors。

所以,它就像:

items  = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

你似乎混淆了 [NSArray sortedArrayUsingDescriptors][NSMutableArray sortUsingDescriptors]。后者仍然存在,没有被替换掉。 - Dalzhim

0
array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];

记得将值赋给数组


0

编写一个排序函数,比较两个字典中的相关字段。一旦你有了这个版本,你就可以例如使用NSArray#sortedArrayUsingFunction:context:来对你的数组进行排序。

请参阅NSArray Class Reference


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