4

I am trying to sort an array of prices from low to high. I have it working but not the way I want it to. Long story short, the sorter is putting numbers in order like this: 100 10900 200 290

instead of sorting like this

100 200 290 10900

here is my code I am doing this with.

-(void)filterPriceLowHigh {
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"ListPrice"
        ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray *sortedArray;
    sortedArray = [app.vehiclesArrayToDisplay
        sortedArrayUsingDescriptors:sortDescriptors];
    [app.vehiclesArrayToDisplay removeAllObjects];
    [app.vehiclesArrayToDisplay addObjectsFromArray:sortedArray];
}

Could someone tell me what I need to do here? thanks in advance.

JOM
  • 8,139
  • 6
  • 78
  • 111
Louie
  • 5,920
  • 5
  • 31
  • 45
  • 1
    I don't want to be Captain Obvious, but the numbers are sorted like strings. Did you check the datatype of that field? – Goran Jovic Dec 28 '10 at 23:36
  • yes the "listprice" is a string - what would i need to do/convert in order to get them to sort the way i want? – Louie Dec 28 '10 at 23:40

2 Answers2

10

Create the sort descriptor like this:

sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"ListPrice"
                                               ascending:YES
                                              comparator:^(id obj1, id obj2) {
    return [obj1 compare:obj2 options:NSNumericSearch];
}];
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • Excellent!! thanks for this... i thought id definitely have to convert my string but not with this chunk of code. - thanks again. – Louie Dec 28 '10 at 23:58
  • Btw, you can sort `vehiclesArrayToDisplay` in place with `-sortUsingDescriptors:`. No need to create a separate NSArray. – Ole Begemann Dec 29 '10 at 00:04
  • @OleBegemann Unfortunately, I can't use SortDescriptor with comparator in CoreData FetchRequest :( – onmyway133 Nov 07 '13 at 17:23
0

You need to convert your NSString's to NSNumbers first. Look at the documentation for NSNumberFormatter and the instance method numberFromString.

Felix
  • 35,354
  • 13
  • 96
  • 143