[英]Sorting array of dictionaries by number
所以我有一个包含约180个字典的数组,每个字典中有5个对象(3个字符串和2个NSNumber)
我正在尝试通过其属性之一对每个字典进行排序,这对于字符串来说可以很好地工作,但是当涉及到数字时,它无法正确排序。
-(void) sortArrayBy:(int)sortingNumber {
switch (sortingNumber) {
case 0:
NSLog(@"sorting by atomicnumber");
[self.elementsArray sortUsingDescriptors:[NSArray arrayWithObjects:
// When sorting this comes back the same each time but not in the correct order
[NSSortDescriptor sortDescriptorWithKey:@"ATOMIC NUMBER" ascending:YES], nil]];
break;
case 1:
NSLog(@"sorting by name");
[self.elementsArray sortUsingDescriptors:[NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:@"ELEMENT NAME" ascending:YES], nil]];
break;
case 2:
NSLog(@"sorting by symbol");
[self.elementsArray sortUsingDescriptors:[NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:@"CHEMICAL SYMBOL" ascending:YES], nil]];
break;
case 3:
NSLog(@"sorting by mass");
// When sorting this comes back the same each time but not in the correct order
[self.elementsArray sortUsingDescriptors:[NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:@"ATOMIC MASS" ascending:YES], nil]];
break;
default:
break;
}
好的,所以我想出了问题,由于某种原因,它是按第一个数字而不是整个整数排序的,所以我使用以下代码:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor
sortDescriptorWithKey:@"ATOMIC MASS" ascending:YES comparator:^(id obj1, id obj2) {
return [obj1 compare:obj2 options:NSNumericSearch];
}];
[self.elementsArray sortUsingDescriptors:[NSArray arrayWithObjects: sortDescriptor, nil]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.