gpt4 book ai didi

ios - 按数字对字典数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:46:15 27 4
gpt4 key购买 nike

所以我有一个包含大约 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]];

关于ios - 按数字对字典数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17920564/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com