使用NSSortDescriptor排序数组不起作用

时间:2014-02-20 12:42:54

标签: ios objective-c sorting nsmutablearray nssortdescriptor

我有一个包含多个字典的数组:

 {
    highRate = "600.49";
    hotelId = 439607;
    hotelRating = "2.5";
    latitude = "12.97153";
    longitude = "80.15096";
    lowRate = "600.49";
    name = "Hotel Kingss Park";
    proximityDistance = "17.999475";
    thumbNailUrl = "http://images.travelnow.com/hotels/7000000/6510000/6500300/6500296/6500296_3_t.jpg";
    tripAdvisorRating = "4.0";
},
    {
    highRate = "990.0";
    hotelId = 327929;
    hotelRating = "2.0";
    latitude = "13.06931";
    longitude = "80.2706";
    lowRate = "450.45";
    name = "Mallika Residency";
    proximityDistance = "1.6274245";
    thumbNailUrl = "http://images.travelnow.com/hotels/3000000/2960000/2958400/2958303/2958303_2_t.jpg";
    tripAdvisorRating = "2.5";
}

我尝试使用 lowRate 键对此数组进行排序。

NSSortDescriptor *rating_Sort = [NSSortDescriptor sortDescriptorWithKey:@"lowRate" ascending:NO];
NSArray *descriptorArray = [NSArray arrayWithObject:rating_Sort];

NSArray *sortedArray = [self.tblDisplayArray sortedArrayUsingDescriptors:descriptorArray];

这里 self.tblDisplayArray 是我的数组。

但是没有在Result中获得正确的排序数组。

为什么会这样?

5 个答案:

答案 0 :(得分:5)

它们都是字符串,所以它试图按字母顺序排序,而不是数字排序。尝试:

NSSortDescriptor *desc = [[NSSortDescriptor alloc]initWithKey:@"doubleValue" ascending:YES];

或使用NSNumbers代替NSString ... @()而不是@“”。

@Rajesh是正确的,并非所有数字都是整数,所以你应该使用doubleValue,我已经更新了代码!

希望这有帮助! :)

答案 1 :(得分:3)

更改此

 NSSortDescriptor *rating_Sort = [NSSortDescriptor sortDescriptorWithKey:@"lowRate.doubleValue" ascending:NO];

它工作正常。

答案 2 :(得分:0)

你的字符串数组实际上是双值。所以你按如下方式对描述符进行排序。

    NSSortDescriptor *aSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES comparator:^(id obj1, id obj2) {
    if ([obj1 doubleValue] < [obj2 doubleValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
   }];
   sortedArray = [yourArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];

答案 3 :(得分:0)

正如@Georgegreen指出的那样,它们都是字符串,所以它试图按字母顺序排序,而不是数字排序。

但你应该使用float或double来精确而不是int。

NSSortDescriptor *desc = [[NSSortDescriptor alloc]initWithKey:@"doubleValue" ascending:YES];

答案 4 :(得分:0)

或者只是这样做:

NSArray *sortedArray = [[yourTempArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];