views:

711

answers:

2

Hi,

I'm struggling with trying to sort an array of dictionarys.

My dictionaries have a couple of values of interest, price, popularity etc.

Any suggestions?

A: 

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 http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/doc/uid/20000137-BBCHBAHB

St3fan
+3  A: 

Use NSSortDescriptor like this..

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest"  ascending:YES];
    [stories sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    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

Warrior
+1 This is by far the simplest method
Dave DeLong
Many thanks, makes sense and works
Andrew
This 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
NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES] autorelease]; [stories sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
Tom Andersen