在目标c中对负数和正数进行排序

时间:2013-08-29 11:49:17

标签: iphone ios objective-c nsarray nsdictionary

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

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响应的日志

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

4 个答案:

答案 0 :(得分:4)

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按降序排列,则交换中的num1和num2     退货声明。

答案 1 :(得分:2)

如果价格存储为NSNumber个对象,那么来自@ trojanfoe链接(Best way to sort an NSArray of NSDictionary objects?)的方法应该有效:

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

但是从你上次评论看来,价格似乎存储为字符串。 在这种情况下,以下工作,因为floatValue将每个字符串转换为a 浮点值:

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

答案 2 :(得分:1)

您没有对数字进行排序。根据常见的“价格”元素,您正在对字典进行排序:

sortedArray = [numberArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
    return [a[@"price"] compare:b[@"price"]];
}];

答案 3 :(得分:0)

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