user2606782
user2606782

Reputation: 320

How to maintain the order of key added in NSMutableDictionary

I didn't knew this at first place, I thought that the key/value pair I am adding to my dictionary will be in the same order when I try to retrieve it back...

Now here is my question -

I have a ViewController which I have made as singleton, inside this VC I have defined:

@property (nonatomic) NSMutableDictionary *dictionary;

Now I try accessing this dictionary from various other classes and set its contents via:

[[[ViewController sharedViewController] dictionary] setValue:[NSNumber numberWithBOOL:NO] forKey:@"xx"] , yy ,zz and so on

I have my delegates implemented which would hit for a particular key(xx,yy,zz and so on). Now whenever a particular delegate method is hit I need to update my dictionary with same key but [NSNumber numberWithBOOL:YES] which is happening .. but the order in which I added the items in dictionary is not maintained ... How can I achieve this?? I need to maintain the order in the same way in which I have added my items to the dictionary at first place??

Can someone please help me out??

Upvotes: 1

Views: 1871

Answers (3)

Nat
Nat

Reputation: 12952

As pointed, you should use NSArray to have your values ordered. You can also use some 3rd party APIs like: M13OrderedDictionary or others, however, that's not a pretty solution.

Obviously, the desired solution is to create your own object or struct and keep an array of those objects/structs.

Upvotes: 2

Samuel Chow
Samuel Chow

Reputation: 26

You can make a copy of key by using the following code:

NSArray *allKeys = [dictionary allKeys];

Then, the keys all saved in order and you can access particular value by getting specific key in allKeys array and retrieving it by using dictionary[allKeys[2]].

Upvotes: 0

Gavin
Gavin

Reputation: 8200

NSDictionary is just a mapping between keys and values that has no defined order. If you try to iterate over the keys, you may or may not get them back in the same order you added them, and you should never depend on the ordering of the keys when iterating over them.

One thing you could do is create an NSArray that contains the keys in the order you want them. Then you can iterate over the keys in the array and get the values from the NSDictionary in the order you wanted. The combination of these two basically gives you a sorted key NSDictionary.

Another thing you could do is to just use an NSArray to stores the values, unless the keys that you're using matter as well. But if all you're trying to do is get the values in a certain order, then I would say NSArray should work fine.

Upvotes: 1

Related Questions