所以我有一个包含大约180个字典的数组,每个字典中有5个对象(3个字符串和2个NSNumbers)
我试图通过其中一个属性对每个字典进行排序,这对字符串工作正常,但是当它涉及数字时,它没有正确排序。
-(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;
}
答案 0 :(得分:4)
好的,所以我想出了问题,由于某种原因它是按第一个数字排序而不是整数,所以我使用这个代码:
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]];