开发者

How to sort numbers in array from low to high

开发者 https://www.devze.com 2023-02-01 06:48 出处:网络
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:

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 开发者_如何学Golike 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.


Create the sort descriptor like this:

sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"ListPrice"
                                               ascending:YES
                                              comparator:^(id obj1, id obj2) {
    return [obj1 compare:obj2 options:NSNumericSearch];
}];


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

0

精彩评论

暂无评论...
验证码 换一张
取 消