Best way to sort an NSArray of NSDictionary objects?
45,065
Solution 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
Solution 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.
Solution 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];
Solution 4
Update , sortUsingDescriptors is now sortedArrayUsingDescriptors
So, its like:
items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
Author by
iOSDevil
Updated on June 30, 2020Comments
-
iOSDevil almost 4 years
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?
-
Tom Andersen over 13 yearsThis is good, but it does leak. 1) the sort descriptor should be released or autoreleased, and 2) The copy call is not needed the line can be deleted.
-
Tom Andersen over 13 yearsNSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES] autorelease]; [stories sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
-
maxcanna over 12 yearsYou can use NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"interest" ascending:YES];
-
J3RM over 11 yearsrecent = [[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]] copy];
-
johndpope over 11 yearsNSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; [resultArray1 sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
-
Rob almost 11 yearsYou need to store the output during the sort call: NSArray* recent = [stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
-
Dalzhim about 10 yearsYou seem to be confusing -
[NSArray sortedArrayUsingDescriptors]
and -[NSMutableArray sortUsingDescriptors]
. The latest still exists and hasn't been replaced. -
Rambatino almost 10 yearsYou little star. this helped me sort a sub sub dictionary. Thanks a lot!
-
Rambatino almost 10 yearsIt doesn't answer the question!
-
Mrugesh Tank over 7 yearsCan I use "@allkey" type value in init of sortDescriptor ?
-
Victor Kwok over 5 yearsif stories is a mutable array, you can use [stories sortUsingDescriptors:@[descriptor]]; instead