Best way to sort an NSArray of NSDictionary objects?

IosObjective CSortingNsarrayNsdictionary

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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 - Ios

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

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 - Ios

Update , sortUsingDescriptors is now sortedArrayUsingDescriptors

So, its like:

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

Solution 5 - Ios

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

Solution 6 - Ios

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

Remember assign to array

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniOSDevilView Question on Stackoverflow
Solution 1 - IosWarriorView Answer on Stackoverflow
Solution 2 - Iossuperarts.orgView Answer on Stackoverflow
Solution 3 - IosAnsari AwaisView Answer on Stackoverflow
Solution 4 - IosdijipijiView Answer on Stackoverflow
Solution 5 - IosStefan ArentzView Answer on Stackoverflow
Solution 6 - IosAngus LamView Answer on Stackoverflow