NSDictionary sort by keys as floats

为君一笑 提交于 2019-12-20 09:59:46

问题


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


回答1:


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];
    …



回答2:


You can't sort a dictionary, but you can get the keys as an array, sort that, then output in that order. sortedArrayUsingComparator will do that, and you can compare the strings with the NSNumericSearch option.

NSArray* keys = [myDict allKeys];
NSArray* sortedArray = [keys sortedArrayUsingComparator:^(id a, id b) { 
    return [a compare:b options:NSNumericSearch]; 
}]; 

for( NSString* aStr in sortedArray ) {
    NSLog( @"%@ has key %@", [myDict objectForKey:aStr], aStr );
}



回答3:


Use compare:options: with NSNumericSearch.



来源:https://stackoverflow.com/questions/3779739/nsdictionary-sort-by-keys-as-floats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!