i have created NSMutableDictionary with 10 keys.Now i want to access NSMutableDictionary keys in a same order as it was added to NSMutableDictionary (using SetValue:* forKey:* );
How can i achieve that ?
i have created NSMutableDictionary with 10 keys.Now i want to access NSMutableDictionary keys in a same order as it was added to NSMutableDictionary (using SetValue:* forKey:* );
How can i achieve that ?
If you absolutely must use a dictionary container, you have to use a key that is sortable by the order in which you add key-value pairs. Thus, when creating your dictionary, you use a key that is an auto-incrementing integer or similar. You can then sort on the (integer) keys and retrieve the values associated with those keys.
If you do all of that, however, you may as well just use an
NSMutableArray
and add values to the array directly! It will be much faster and require less code. You just retrieve objects in order:NSMutableDictionary
can't do that. Take a look at e.g. Matt GallaghersOrderedDictionary
.I wrote a quick method to take a source array (of objects that are all out of order) and a reference array (that has objects in a desired (and totally arbitrary) order), and returns an array where the items of the source array have been reorganized to match the reference array.
Note that this is very fragile. It uses
NSArray
'scontainsObject:
method, which ultimately will callNSObject
'sisEqual:
. Basically, it should work great for arrays ofNSString
s,NSNumber
s, and maybeNSDate
s (haven't tried that one yet), but outside of that, YMMV. I imagine if you tried to pass arrays ofUITableViewCell
s or some other really complex object, it would totally sh*t itself, and either crash or return total garbage. Likewise if you were to do something like pass an array ofNSDate
s as the reference array and an array ofNSString
s as the source array. Also, if the source array contains items not covered in the reference array, they'll just get discarded. One could address some of these issues by adding a little extra code.All that said, if you're trying to do something simple, it should work nicely. In your case, you could build up the reference array as you are looping through your
setValue:forKey:
.Then, when you want to loop over your items in the order they came in, you just
Although @GenralMike 's answer works a breeze, it could be optimized by leaving off the unnecessary code as follows:
1) Keep an array to hold reference to the dictionary keys in the order they are added.
2) Now the "referenceArray" holds all of the keys in order, So you can retrieve objects from your dictionary in the same order as they were originally added to the dictionary.
Actually you have a reference array in order manner then why you have to add to one more array.So i guess this approach is not good.Please consider my opinion.