Search code examples
iosobjective-csortingdictionarynsdictionary

Get all key values from NSDictionary in order Objective C


I need to get all keys of a Dictionary with its values.

for example

I have a dictionary like:

{
    "Last_Settled_Amount" = "7056.92";
    "Last_Settled_Date" = "2021-03-25T00:00:00";
    "Net_Settled_Amount" = "17810.23";
    "Settled_Adjustment_Amount" = "-79";
    "Settled_Tx_Amount" = 7202;
    "Settled_Tx_Fees" = "57.46";
    "Settled_Tx_VAT" = "8.619999999999999";
    "Total_Payment_Count" = 3;
    "Total_Settled_Tx" = 22;
    "Transfer_Charge" = 0;
}

I want to get its key values so I implement it like this

for (NSString* key in [dd allKeys]) {

        id value = [dd objectForKey:key];
        NSLog(@"areacodedisplay: value = %@",value);
        NSLog(@"areacodedisplay: key = %@",key);
   }

I am able to get all keys and values But its not in order. I want the same order as I got them in the dictionary.


Solution

  • Dictionaries are unordered, however it seems that you want the keys in alphabetical order, so you can sort the allKeys array.

    for (NSString* key in [[dd allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
        id value = [dd objectForKey:key];
        NSLog(@"areacodedisplay: value = %@",value);         
        NSLog(@"areacodedisplay: key = %@",key);
    }
    

    If you want the values in a specific, but arbitrary order then you would need to resort to accessing each value directly.