Best way to sort NSArray NSDictionary objects?

I am trying to sort an array of dictionaries.

My dictionaries have a couple of meanings of interest, price, popularity, etc.

Any suggestions?

+63
sorting ios objective-c nsarray nsdictionary
Mar 06 '10 at 17:27
source share
6 answers

Use an 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 that has sorted dictionary values. Change @"interest" to the key value to be sorted.

All the best

+190
Mar 06
source share
 [array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]]; 

I really do not want to break it into several lines. This is easy enough for me.

+24
Dec 29 '11 at 8:35
source share

You can simply go from the parent to the desired child property. E.g.

 NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child" ascending:YES]; 
+9
Apr 21 '14 at 12:57 on
source share

Update, sortUsingDescriptors is now sorted. ArrayUsingDescriptors

So its kind of:

 items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]; 
+4
Apr 13 2018-12-12T00:
source share

Write a sort function that compares the corresponding fields in two dictionaries. If you have this version, you can, for example, use NSArray#sortedArrayUsingFunction:context: to sort your array.

See NSArray Class Help

0
Mar 06 '10 at 17:36
source share
 array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]]; 

Remember assignment to an array

0
Jun 02 '16 at 10:16
source share



All Articles