Pat_Morita Pat_Morita - 7 months ago 30
Objective-C Question

NSDictionary to ordered NSArray

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",

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

Basically i need the opposite of this method:

- keysSortedByValueUsingComparator: // -> valuesSortedByKeyUsingComparator:

Any help appreciated.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download