ios 对 NSDictionary 对象的 NSArray 进行排序的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2393386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to sort an NSArray of NSDictionary objects?
提问by iOSDevil
I'm struggling with trying to sort an array of dictionaries.
我正在努力尝试对一系列字典进行排序。
My dictionaries have a couple of values of interest, price, popularity etc.
我的字典有几个兴趣、价格、受欢迎程度等值。
Any suggestions?
有什么建议?
回答by Warrior
Use NSSortDescriptor
like this..
NSSortDescriptor
像这样使用..
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES];
stories = [stories sortedArrayUsingDescriptors:@[descriptor]];
recent = [stories copy];
stories
is the array you want to sort. recent
is another mutable array which has sorted dictionary values. Change the @"interest"
with the key value on which you have to sort.
stories
是要排序的数组。recent
是另一个已排序字典值的可变数组。@"interest"
使用您必须排序的键值更改。
All the best
祝一切顺利
回答by superarts.org
[array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
I don't really want to break it into multiple lines. It's already simple enough for me.
我真的不想把它分成多行。对我来说已经足够简单了。
回答by Ansari Awais
You can just traverse from the parent to the required child property. For e.g.
您可以从父属性遍历到所需的子属性。例如
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child" ascending:YES];
回答by dijipiji
Update , sortUsingDescriptors is now sortedArrayUsingDescriptors
更新, sortUsingDescriptors 现在是 sortedArrayUsingDescriptors
So, its like:
所以,它就像:
items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
回答by Stefan Arentz
Write a sort function that compares the relevant fields in two dictionaries. When you have this version you can for example use NSArray#sortedArrayUsingFunction:context:
to sort your array.
编写一个排序函数,比较两个字典中的相关字段。例如,当您拥有此版本时,您可以用于NSArray#sortedArrayUsingFunction:context:
对数组进行排序。
回答by Angus Lam
array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
Remember assign to array
记住分配给数组