How to sequentialy access a dictionary?
I want to access the dictionary the way element was stored in it. Could anybody 开发者_C百科help me do this. Thanks in advance!!
Dictionaries store its values in a structure indexed by keys or more precisely by a hash values of keys. This is why they are fast. They do not need to search for values, they just take the has values of a key and go straight for the value (in most cases, only in case of colliding key hash values they have to search).
So the order in which values are being saved is not predictable. If you need the order you need an Array or Linked List - both structures have a defined order in which values are being stored.
If you need both: dictionary-type access and preservation of order you would have to look for a possibly open source library with a list backed dictionary or do you own version: take a dictionary interface and implement it so that it gets saved in a lists and internal dictionary at the same time.
Accessor methods would go to the dictionary but you could provide iterators that go for the list and return data in the order of addition.
There isn't an Ordered Dictionary in Cocoa. Your best bet is to create a custom class which wraps a dictionary and keeps an array of the keys as they are entered. This isn't too hard. Your class could very well "cover" the methods of NSMutableDictionary
, something like this:
// innerDict is an NSMutableDictionary
// keyArray is an NSMutableArray
- (void)setObject:(id <NSCopying>)anObject forKey:(id)aKey {
[innerDict setObject:anObject forKey:aKey];
// Keys are added to the array in the order they go into the dictionary;
// users of the class can access the array to get this info
[keyArray addObject:aKey];
}
- (id)objectForKey:(id)aKey {
return [innerDict objectForKey:aKey];
}
- (void)removeObjectForKey:(id)aKey {
[innerDict removeObjectForKey:aKey];
[keyArray removeObject:aKey];
}
- (NSEnumerator *)keyEnumerator {
// It's actually better for users of this class to
// use fast enumeration on the keyArray; this is just an example
return [keyArray objectEnumerator];
}
If you're into getting your hands dirty, Matt Gallagher has a tutorial on collection subclassing that just so happens to use Ordered Dictionary as an example.
精彩评论