Kazzar
Kazzar

Reputation: 1442

Sorting an NSArray of NSDictionary

I have to sort an array of dictionaries but I have to order by an object in the dictionaries.

Upvotes: 3

Views: 6279

Answers (3)

Alex Milde
Alex Milde

Reputation: 511

here is an implementation with custom objects instead of dictionaries:

ArtistVO *artist1 = [ArtistVO alloc];
artist1.name = @"Trentemoeller";
artist1.imgPath = @"imgPath";

ArtistVO *artist2 = [ArtistVO alloc];
artist2.name = @"ATrentemoeller";
artist2.imgPath = @"imgPath2";


ArtistVO *artist3 = [ArtistVO alloc];
artist3.name = @"APhextwin";
artist3.imgPath = @"imgPath2";    

//NSLog(@"%@", artist1.name);
NSMutableArray *arr = [NSMutableArray array];
[arr addObject:artist1];
[arr addObject:artist2];
[arr addObject:artist3];


NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc]
  initWithKey:@"name"
  ascending:YES
  selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];    

NSArray * descriptors =
[NSArray arrayWithObjects:lastDescriptor, nil];
NSArray * sortedArray =
[arr sortedArrayUsingDescriptors:descriptors];    

NSLog(@"\nSorted ...");
NSEnumerator *enumerator;
enumerator = [sortedArray objectEnumerator];

ArtistVO *tmpARt;
while ((tmpARt = [enumerator nextObject])) NSLog(@"%@", tmpARt.name);

Upvotes: 0

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

Use NSSortDescriptors with -sortedArrayUsingDescriptors:. For the key path, pass in the dictionary key, followed by the object's key(s) by which you want to sort. In the following example, you have an array of dictionaries and those dictionaries have a person under "personDictionaryKey", and the "person" has a "lastName" key.

NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey:@"personInDictionary.lastName" 
        ascending:YES] autorelease]; // 1
NSArray * sortedArray = [unsortedArray sortedArrayUsingDescriptors:
        [NSArray arrayWithObject:descriptor]];

1 - In 10.6 there are class convenience methods for creating sort descriptors but as bbum's answer says, there are now blocks-enabled sorting methods and I'm betting they're a lot faster. Also, I noticed your question is for iOS, so that's probably irrelevant. :-)

Upvotes: 13

bbum
bbum

Reputation: 162712

To rephrase; you want to sort the array by comparing dictionary contents? (I.e. you know you can't sort a dictionary's contents, right?)

As Joshua suggested, use NSSortDescriptor and sortedArrayUsingDescriptors:. This is quite likely the best solution; at least the most straightforward.

There are other ways, too.

Assuming you are targeting iOS 4.0, then you can use sortedArrayUsingComparator: and pass a block that'll do the comparison of the two dictionary's contents.

If you are targeting iOS 3.x (including the iPad), then you would use sortedArrayUsingFunction:context:.

Or, as Joshua suggested, use NSSortDescriptor and sortedArrayUsingDescriptors:

All are quite well documented, with examples.

Upvotes: 1

Related Questions