我希望根据浮点数height
参数对数组数据进行排序。我使用NSSortDescriptor
但它不起作用。
以下是我的代码:
NSSortDescriptor *hDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Height" ascending:YES];
NSArray *sortDescriptors = @[hDescriptor];
[[[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"] sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"%@",[[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"]); // height is printed in random order. not sorted
我该如何解决这个问题?
已编辑:日志
(
{
Height = "11.5766";
Name = "abc";
},
{
Height = "11.8443";
Name = "sdfsdf";
},
{
Height = "12.211";
Name = "hnkhjk";
},
{
Height = "13.7271";
Name = "ertert";
},
{
Height = "15.2694";
Name = "sdf";
},
{
Height = "21.9242";
Name = "fgh";
},
{
Height = "23.0857";
Name = "ert";
},
{
Height = "6.48365";
Name = "cvb";
},
{
Height = "7.5204";
Name = "rt";
},
{
Height = "8.67856";
Name = "asd";
}
)
答案 0 :(得分:1)
-sortedArrayUsingDescriptors:sortDescriptors:
返回已排序的数组。所以你基本上只是对它进行排序并丢弃结果。
您需要对此值进行排序并将其分配给您将其拉出的NSDictionary
。
NSArray *persons = [[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"];
NSArray *sortedPersons = [persons sortedArrayUsingDescriptors:sortDescriptors];
[[appDelegate.arr objectAtIndex:section] setObject:sortedPersons forKey:@"arrPerson"];
但要做到这一点,你需要NSMutableDictionary
。如果您在问题中发布更多代码,则可能有所帮助。但以上是你的问题:)
编辑:
根据评论中的讨论,值存储为NSString
s
以下将尝试将任何字符串转换为数字(以及任何其他类型):
NSArray *sorters = @[[NSSortDescriptor sortDescriptorWithKey:@"Height" ascending:YES comparator:^(id obj1, id obj2) {
NSNumber *n1;
NSNumber *n2;
// Either use obj1/2 as numbers or try to convert them to numbers
if ([obj1 isKindOfClass:[NSNumber class]]) {
n1 = obj1;
} else {
n1 = @([[NSString stringWithFormat:@"%@", obj1] doubleValue]);
}
if ([obj2 isKindOfClass:[NSNumber class]]) {
n2 = obj2;
} else {
n2 = @([[NSString stringWithFormat:@"%@", obj2] doubleValue]);
}
return [n1 compare:n2];
}]];
NSArray *persons = [[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"];
NSArray *sortedPersons = [persons sortedArrayUsingDescriptors:sorters];
[[appDelegate.arr objectAtIndex:section] setObject:sortedPersons forKey:@"arrPerson"];
如果您可以保证Height
值始终为NSString
或NSNumber
(如果我们正在处理JSON,则不是NSNull
)以下排序描述符也可以起作用:
NSArray *sorters = @[[NSSortDescriptor sortDescriptorWithKey:@"Height.doubleValue" ascending:YES]];
虽然第一个排序描述符有点长,但如果将任何其他对象放在Height
值之内,它也会更加健壮,因为那样会出现class is not key value coding-compliant for the key length
错误。
答案 1 :(得分:1)
试试这个可行。
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Height"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [[[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"]sortedArrayUsingDescriptor:sortDescriptors];