How can I preserve the way that I add objects to NSDictionary
?
I realize that there is no specific order to values in NSDictionary
, but in my case I need the preserve the order that I add using setValue:forKey:
, like an array.
How could I do this?
Any help appreciated.
Dictionary is hash mapped for faster retrieval. You are not allowed to fix its order.
If you want to store in order you should use arrays.
Or you have to use some complex way, keep on appending an int orderNumber
(You need to increment it after every setObject/setValue) with the key. to storing and retrieval as :
NSDictionary *dict=[NSDictionary new];
NSString *key=....;
[dict setValue:@"some value" forKey:[NSString stringWithFormat:@"%d-%@",orderNumber, key]];
Alternatively you can use an array having one dictionary per index.
Another way would be to use a custom class as
@interface ....
@property(...) NSInteger index;
@property(...) NSString *key;
@property(...) id object;
// and methods to retrieve based on key, based on index etc
@end
EDIT 2:
Found very similar to what I posted an year ago, see this OrderedDictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With