Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array by its members' dictionary's keys

Tags:

objective-c

If that was a little confusing here's a visual representation:

Array > Object > Dictionary > Values

Here's some context if this helps:

An array contain playlists. Each playlist has a dictionary. Each dictionary contains metadata.

I need to sort the original dictionary by this metadata.

I've been pretty stumped at implementing this. Thoughts?

[Edit] Changed the higher dictionary into an array

like image 427
Nosrac Avatar asked Jul 28 '26 10:07

Nosrac


1 Answers

You want to use at least one NSSortDescriptor. This is basically an abstract way of representing a way to sort something. It can contain a key path (more on that in a second) or a function pointer, or some other way to compare two objects.

You'll probably want to use it with a key path. So if you have an array of Foo objects, and they have a "dictionary" property that returns an NSDictionary, and you want to sort the array based on a value in the dictionary under the key @"bar", then the sort descriptor you'd create would be:

[NSSortDescriptor sortDescriptorWithKey:@"dictionary.bar" ascending:YES]

From here you can use -[NSArray sortedArrayUsingDescriptors] and pass it an array containing this NSSortDescriptor.

like image 76
Dave DeLong Avatar answered Aug 02 '26 06:08

Dave DeLong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!