使用嵌套字典按包含浮点数的字符串值对数组进行排序

时间:2014-08-13 15:20:07

标签: objective-c arrays sorting dictionary

我拥有的是

NSSortDescriptor *sortDescriptorNearest = [NSSortDescriptor sortDescriptorWithKey:@"petrolStation.pointCoordinates.distance" ascending:YES];
_nearestList = (NSMutableArray *)[_gasStations sortedArrayUsingDescriptors:@[sortDescriptorNearest]];

在此之后,_nearestList按距离的字符串比较排序:

distance: 11242.591384
distance: 11255.886503
distance: 11473.600818
distance: 11547.162685
distance: 11772.008008
distance: 11838.271283
distance: 12012.219580
distance: 12054.000451
distance: 12775.864654
distance: 13878.021040
distance: 14941.605403
distance: 15011.424101
distance: 1513.702794
distance: 17359.161771
distance: 1795.865052
distance: 19494.251275
distance: 19494.821685

但我想按浮点值排序。我怎样才能做到这一点?

谢谢。 :)

1 个答案:

答案 0 :(得分:1)

我明白了:)

NSComparator compareDistances = ^(id string1, id string2)
{
    NSNumber *number1 = [NSNumber numberWithFloat:[string1 floatValue]];
    NSNumber *number2 = [NSNumber numberWithFloat:[string2 floatValue]];

    return [number1 compare:number2];
};

// sort list and create nearest list
NSSortDescriptor *sortDescriptorNearest = [NSSortDescriptor sortDescriptorWithKey:@"petrolStation.pointCoordinates.distance" ascending:YES comparator:compareDistances];
_nearestList = (NSMutableArray *)[_gasStations sortedArrayUsingDescriptors:@[sortDescriptorNearest]];