user2543991
user2543991

Reputation: 625

Sort an NSArray of NSDictionary

I have an NSArray of NSDictionary unsortedArray look like:

  ( 
    {symbol = "ABC"; price = "9.01";}
    {symbol = "XYZ"; price = "3.45";}
    ...
  (

Here is the sorting code:

  NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES];
  NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
  NSArray *sortArray = [unsortedArray sortedArrayUsingDescriptors:sortedDescriptors];

  NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"symbol" ascending:YES];
  NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
  NSArray *sortArray = [unsortedArray sortedArrayUsingDescriptors:sortedDescriptors];

The sorting results for symbol key is ok but for price key is not sorted. What could be wrong? The price is in NSString but want to sort it look like

  3.45
  9.01
  ...

Thanks in advance.

Upvotes: 0

Views: 117

Answers (1)

SPA
SPA

Reputation: 1289

use NSNumber for the price in the dictionary and the sort descriptor will work on the numerical value rather than as a string, e.g.

NSArray *dictArray = @[ @{@"symbol" : @"ABC", @"price" : @9.01},
                        @{@"symbol" : @"XYZ", @"price" : @3.45} ];

or, if the price is a string

NSArray *dictArray = @[ @{@"symbol" : @"ABC", @"price" : @"9.01"},
                        @{@"symbol" : @"XYZ", @"price" : @"3.45"} ];

use a comparator which requires comparing the price of a pair of dictionaries, e.g.

    NSArray *sortedArray = [dictArray
                        sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dict1,
                                                                       NSDictionary *dict2) {

    double price1 = [[dict1 valueForKey:@"price"] doubleValue];
    double price2 = [[dict2 valueForKey:@"price"] doubleValue];

    if(price1 > price2)
        return (NSComparisonResult)NSOrderedDescending;

    if(price1 < price2)
        return (NSComparisonResult)NSOrderedAscending;

    return (NSComparisonResult)NSOrderedSame;

}];

Upvotes: 2

Related Questions