Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary sort by keys as floats

basically I have an NSDictionary with keys and values.

The keys are all numbers, but at the moment they are strings.

I want to be able to compare them as numbers in order to sort them.

eg: If I have a Dictionary like this:

{
  "100"  => (id)object,
  "20"   => (id)object,
  "10"   => (id)object,
  "1000" => (id)object,
}

I want to be able to sort it like this:

{
  "10"   => (id)object,
  "20"   => (id)object,
  "100"  => (id)object,
  "1000" => (id)object,
}

Any ideas?

Thanks

Tom

like image 629
Thomas Clayson Avatar asked Sep 23 '10 15:09

Thomas Clayson


1 Answers

Not sure what you are up to – dictionaries are inherently unsorted, there is no stable key ordering in the default implementation. If you want to walk the values by sorted keys, you can do something like this:

NSInteger floatSort(id num1, id num2, void *context)
{
    float v1 = [num1 floatValue];
    float v2 = [num2 floatValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

NSArray *allKeys = [aDictionary allKeys];
NSArray *sortedKeys = [allKeys sortedArrayUsingFunction:floatSort context:NULL];
for (id key in sortedKeys)
    id val = [aDictionary objectForKey:key];
    …
like image 153
zoul Avatar answered Sep 25 '22 03:09

zoul