Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered NSDictionary

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.

like image 387
Jack Greenhill Avatar asked Nov 03 '22 06:11

Jack Greenhill


1 Answers

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.

like image 53
Anoop Vaidya Avatar answered Nov 15 '22 09:11

Anoop Vaidya