Pergunta

I have a NSDictionary with currency-codes as keys and as values another NSDictionary inside containing a NSString (currency name) + a NSArray (list of coins):

Plist

The goal is to get a NSArray with currency-keys (AED, ARS, ...), sorted by name-value inside.

I know how to sort by keys and values, but can't figure out how to sort by the a value inside a NSDictionary inside a NSDictionary.

The following only gives me a sorted NSArray with the values, but I loose the keys:

NSMutableArray *dictValues = [[self.currencyDict allValues] mutableCopy];

    [dictValues sortUsingComparator: (NSComparator)^(NSDictionary *a, NSDictionary *b)
     {
         NSString *key1 = [a objectForKey: @"name"];
         NSString *key2 = [b objectForKey: @"name"];

         return [key1 compare: key2];
     }
     ];
Foi útil?

Solução

In order to convert a dictionary of dictionaries into an array of dictionaries without losing the key, the first step is to put the key into the dictionary. In other words, you need to convert this

Root
  AED
    name     "some name"
    objects  ...
  ARS
    name     "other name"
    objects  ...

to this

Root
  AED
    name     "some name"
    objects  ...
    key      "AED"
  ARS
    name     "other name"
    objects  ...
    key      "ARS"

and then call allValues and sort the resulting array.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top