Ordered NSDictionary

How can I save a way to add objects to NSDictionary?

I understand that there is NSDictionaryno specific order of values, but in my case I need to keep the order that I add using setValue:forKey:as an array.

How can i do this?

Any help was appreciated.

+5
source share
3 answers

The hash dictionary is displayed for quick searches. You cannot correct your order.

If you want to keep in order, you must use arrays.

Or you need to use some complicated way, add int orderNumber(you need to increase it after each setObject / setValue) using the key. to save and search:

NSDictionary *dict=[NSDictionary new];
NSString *key=....;
[dict setValue:@"some  value" forKey:[NSString stringWithFormat:@"%d-%@",orderNumber, key]];

.


-

@interface ....
    @property(...) NSInteger index;
    @property(...) NSString *key;
    @property(...) id object;
    // and methods to retrieve based on key, based on index etc
@end

2:

, , . OrderedDictionary.

+2

- :

static int index;
[myDictionary setValue:someValue forKey:[NSString stringWithFormat:@"key%d", index++]];
0

You will need:

  • Track the order separately, keeping the key array in the order in which you added them.
  • Add the order as an attribute of the object that you store in the dictionary.

I would prefer the second approach, since it stores all the information in one place. If the object you are storing is not defined by you, you may need to subclass this object or encapsulate it in one of your own objects using an additional order member.

0
source

All Articles