Sorting an array by its members' dictionary's keys
If that was a little confusing here's a visual representation:
A开发者_如何学Pythonrray > 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
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
.
精彩评论