Best way to sort an NSArray of NSDictionary objects?

梦想的初衷 提交于 2019-11-26 03:50:15

问题


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?


回答1:


Use NSSortDescriptor like this..

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.

All the best




回答2:


[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.




回答3:


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];



回答4:


Update , sortUsingDescriptors is now sortedArrayUsingDescriptors

So, its like:

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



回答5:


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.

See NSArray Class Reference




回答6:


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

Remember assign to array



来源:https://stackoverflow.com/questions/2393386/best-way-to-sort-an-nsarray-of-nsdictionary-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!