简体   繁体   中英

Sorting array using NSSortDescriptor is not working

I have an array with multiple dictionary like:

 {
    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";
}

I try to sort this array using lowRate key.

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

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

here self.tblDisplayArray is my array.

But not getting proper sorted array in Result.

Why this happen?

They are all strings so it is attempting to sort them alphabetically not numerically. Try either:

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

or using NSNumbers instead of NSString... @() instead of @"".

@Rajesh is correct, not all your numbers are integers so you should be using doubleValue, I have updated the code!

Hope this helps! :)

change this

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

and it's working fine.

You've array of string which is actually double value. So you sort descriptors as below.

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

As @Georgegreen pointed they are all strings so it is attempting to sort them alphabetically not numerically.

but you should be using float or double to be precise instead of int.

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

或者只是做:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM