Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any alternatives to NSDictionary for unique keys AND unique values?

I'm in the middle of writing some Cocoa classes to parse ID3 tags from MP3 files. To make them as easy to use as possible, I'm allowing the option to request a tag by the actual ID3 frame id ("TCON", "TPE1", "TALB", etc.) or an equivalent word/phrase ("genre", "artist", "album", etc.)

To store this data, currently I have a reference class which returns an NSDictionary with the frame id's as keys, and word/phrases as objects. As I need to look up definitions in both directions, currently I have a second method which returns the dictionary 'switched round', so the words/phrases are the keys.

My question is whether there is a better way to represent this data. Ideally there would be something similar to NSDictionary, the difference being that both the keys and the values must be unique, and you could look up both an "objectForKey:" and a "keyForObject:"

I could write a class for this myself, but I may lose some of the efficiency from hash tables as described in the NSDictionary documentation... also I'd rather keep the number of classes as low as possible in the overall implementation.

Any ideas? Cheers.

like image 370
wipolar Avatar asked Feb 28 '23 14:02

wipolar


1 Answers

Funny you should ask this...

Quinn Taylor, the author of the CHDataStructures framework just added a CHBidirectionalDictionary to the framework last week. It allows you to find objects by key, and find keys by object. It's basically a wrapper around two mutable dictionaries, so you're guaranteed the same lookup time as with a regular dictionary.

The only caveat is that both the object and key must both conform to the NSCopying protocol.

like image 70
Dave DeLong Avatar answered Mar 02 '23 04:03

Dave DeLong