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];
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);
If you want the sortedResult in descending order then interchange the num1 and num2 in
return statement.
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"]];
}];
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;
}];