我有一个 NSArray of NSDictionary unsortedArray 看起来像:
(
{symbol = "ABC"; price = "9.01";}
{symbol = "XYZ"; price = "3.45";}
...
(
排序代码如下:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
NSArray *sortArray = [unsortedArray sortedArrayUsingDescriptors:sortedDescriptors];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"symbol" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
NSArray *sortArray = [unsortedArray sortedArrayUsingDescriptors:sortedDescriptors];
symbol key 的排序结果正常,但 price key 的排序结果未排序。有什么问题吗?价格在 NSString 中,但想要对其进行排序
3.45
9.01
...
提前致谢。
最佳答案
使用 NSNumber 作为字典中的价格,排序描述符将处理数值而不是字符串,例如
NSArray *dictArray = @[ @{@"symbol" : @"ABC", @"price" : @9.01},
@{@"symbol" : @"XYZ", @"price" : @3.45} ];
或者,如果价格是一个字符串
NSArray *dictArray = @[ @{@"symbol" : @"ABC", @"price" : @"9.01"},
@{@"symbol" : @"XYZ", @"price" : @"3.45"} ];
使用需要比较一对字典价格的比较器,例如
NSArray *sortedArray = [dictArray
sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dict1,
NSDictionary *dict2) {
double price1 = [[dict1 valueForKey:@"price"] doubleValue];
double price2 = [[dict2 valueForKey:@"price"] doubleValue];
if(price1 > price2)
return (NSComparisonResult)NSOrderedDescending;
if(price1 < price2)
return (NSComparisonResult)NSOrderedAscending;
return (NSComparisonResult)NSOrderedSame;
}];
关于ios - 对 NSDictionary 的 NSArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19985107/