user2413621
user2413621

Reputation: 2946

how to print the keys in the order in nsmutabledictionary ios

I am getting a response from a server and I am saving it in a dictionary like this, I am using an NSMutableArray for this purpose.

{
    a = "";
    b = "";
    c = "";
    d = "";
}

I want to print the keys in the same order as they are returned from the server.

But when I print the keys the order is: c, d, a, b.

The code I am using is:

for(id key in dic){
    nslog(@"%@",key);
}

How can I do this correctly?

Upvotes: 0

Views: 436

Answers (4)

Sviatoslav Yakymiv
Sviatoslav Yakymiv

Reputation: 7935

NSDictionary and NSMutableDictionary are unordered collections.

But you can use OrderedDictionary.

Upvotes: 1

codester
codester

Reputation: 37189

NSMutableDictionary is unordered collection.You can make your own ordered dictionary subclass and adding the keys to array in order they come.

Have a look here is nice explanation how to make ordered dictionary.You can also use this link

Upvotes: 1

ppalancica
ppalancica

Reputation: 4277

Try to keep the response in an NSMutableArray, where each element is a simple NSDictionary with only one key-value pair.

Upvotes: 1

Wyetro
Wyetro

Reputation: 8588

By nature NSDictionary and NSMutableDictionary are unordered. You would not be able to do it this way. I would suggest storing the keys into an NSArray or NSMutableArray and then printing out the elements of the array in order.

Upvotes: 2

Related Questions