I am trying to sort an array of dictionaries.
My dictionaries have a couple of meanings of interest, price, popularity, etc.
Any suggestions?
Use an NSSortDescriptor like this.
NSSortDescriptor
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.
stories
recent
@"interest"
All the best
[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.
You can simply go from the parent to the desired child property. E.g.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child" ascending:YES];
Update, sortUsingDescriptors is now sorted. ArrayUsingDescriptors
So its kind of:
items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
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.
NSArray#sortedArrayUsingFunction:context:
See NSArray Class Help
array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
Remember assignment to an array