在目标c中对负数和正数进行排序 [英] Sorting negative and positive numbers in objective c

查看:392
本文介绍了在目标c中对负数和正数进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过网络服务列出了一个数量百分比,就像物品的东西一样。我得到的响应是一个类似下面代码的字典数组。我需要它以排序的格式

I am listing out a quantity percentage like stuff for an item via a webservice.The response that I get is an array of dictionaries similar to the below code.I need it in a sorted format

NSArray *numberArray = [NSArray arrayWithObjects:
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:-12.0], @"price", nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:-86.0],@"price", nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:-8.0],@"price", nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:12.0],@"price", nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:2.0],@"price", nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:112.0],@"price", nil], nil];

这是JSON响应的日志

Here's the log of the JSON response

[
    {
        price = "-12";
    },
        {
        price = "-86";
    },
        {
        price = "-8";
    },
        {
        price = 12;
    },
        {
        price = 2;
    },
        {
        price = 112;
    }
]


推荐答案

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

如果您希望sortedResult按降序排列,那么在$ $ b $中交换num1和num2 b return statement。

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

这篇关于在目标c中对负数和正数进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆