0
votes

I am on OSX, objective-c not iOS. I have an NSDictionary like that

NSDictionary* dict = [NSDictionary alloc initWithObjectsAndKeys: 
                @"valueC", @"key3",
                @"valueA", @"key1",
                @"valueB", @"key2",
                nil];

When i call allKeys and allValues of NSDictionary, i get NSArrays. But each time the app runs, the order changes - because NSDictionary is an unordered collection.

What i need is an array that contains all values but ordered after keys, alphabetical, ascending like that:

@[@"valueA", @"valueB",@"valueC"]; //--> ordered after their keys key1,key2,key3

EDIT Basically i need the opposite of this method:

- keysSortedByValueUsingComparator: // -> valuesSortedByKeyUsingComparator:

Any help appreciated.

1
y dont u sort allKeys array as per your requirement ? - Teja Nandamuri
hm... maybe i dont understand you. But i need allValues as array. Sorted after their keys. - Pat_Morita
if you sort the allKeys, then you can enumerate the sorted all keys, and get their value! - Teja Nandamuri
May you explain it with an example? - ah wait, i think i got the idea of it - Pat_Morita

1 Answers

0
votes

You can sort the keys alphabetically first:

   sortedKeyArray = [[mydict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

and enumerate through this sorted array:

[sortedKeyArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    [sortedValueArray addObject:mydict[obj];
}];

Now you have the sorted value in sortedValueArray