flux
flux

Reputation: 395

Sorting array of dictionaries by number

So I have an array with about 180 dictionaries, There are 5 objects in each dictionary (3 strings and 2 NSNumbers)

I am trying to sort each dictionary by one of its properties, this works fine for the strings but when it comes to the number it does not sort correctly.

 -(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;
        }

Upvotes: 2

Views: 357

Answers (1)

flux
flux

Reputation: 395

Ok so I figured out the problem, it was sorting by the first number not the whole number for some reason, so i use this code:

        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]];

Upvotes: 4

Related Questions