View Full Version : Sorting NSMutableArray with NSDictionary inside
alexanderl
Jan 16, 2009, 11:36 PM
Hi All!
(I have to add that Im new to ObjC dev)
I have a NSMutableArray that contains NSDictionary objects, which each contain an object and a float (NSNumber).
Now I want to sort the Array based on the float... How do I do that?
I'm trying with sortUsingSelector: but I dont get it to work....
Thanks for your help!
alex
caveman_uk
Jan 17, 2009, 04:20 AM
Use an NSSortDescriptor.
alexanderl
Jan 18, 2009, 06:24 AM
Thanks caveman_uk!
Ok here is what I got so far (and what doesnt work)
[resultsForThisTestData addObject:[NSDictionary dictionaryWithObjectsAndKeys:dpp, @"DataPoint",
[NSNumber numberWithFloat:distance],@"Distance",nil]];
NSSortDescriptor * sortByDistance = [[[NSSortDescriptor alloc] initWithKey:@"Distance" ascending:TRUE] autorelease];
[resultdata initWithArray:[results sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortByDistance, nil]]];
(hope that is all the code you need)
As I said, this doesnt work and I dont see why?!?!
Thanks!
Alex
stackolee
Sep 12, 2009, 09:53 AM
Check out the official documentation: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Collections/Articles/sortingFilteringArrays.html
This example helped me out:
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc] initWithKey:LAST
ascending:NO
selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
NSSortDescriptor *firstDescriptor =
[[[NSSortDescriptor alloc] initWithKey:FIRST
ascending:NO
selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray *descriptors = [NSArray arrayWithObjects:firstDescriptor, lastDescriptor, nil];
sortedArray = [array sortedArrayUsingDescriptors:descriptors];
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.