Sorting negative and positive numbers in objective c

人走茶凉 提交于 2019-12-01 21:15:28
MobileDev
NSArray *sortedResult = [numberArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSNumber *num1 = [obj1 objectForKey:@"price"];
    NSNumber *num2 = [obj2 objectForKey:@"price"];
    return [num1 compare:num2];
}];
NSLog(@"---%@",sortedResult);

If you want the sortedResult in descending order then interchange the num1 and num2 in
return statement.

Martin R

If the prices are stored as NSNumber objects, then the method from @trojanfoe's link (Best way to sort an NSArray of NSDictionary objects?) should work:

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
NSArray *sorted = [numberArray sortedArrayUsingDescriptors:@[sd]];

But from your last comment it seems that the prices are stored as strings. In that case the following works, because floatValue converts each string to a floating point value:

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"price.floatValue" ascending:YES];
NSArray *sorted = [numberArray sortedArrayUsingDescriptors:@[sd]];

You are not sorting numbers. You are sorting dictionaries, according to a common "price" element:

sortedArray = [numberArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
    return [a[@"price"] compare:b[@"price"]];
}];
Kirsteins
sortedArray = [numberArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    float first  = [(NSNumber *)a[@"price"] floatValue];
    float second = [(NSNumber *)b[@"price"] floatValue];

    if (first > second) {
        return NSOrderedDescending;
    } else if (first < second) {
        return NSOrderedAscending;
    }

    return NSOrderedSame;
}];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!