How can I effectively get key value inverse mapping in NSDictionary?

I map NSString objects to NSNumber objects in NSDictionary to set the enum types from JSON strings as follows:

 typedef enum { XXEnumTypeA, XXEnumTypeB, XXEnumTypeC, } XXEnumType; ... @property (nonatomic, assign) XXEnumType enumType; ... self.mapNSStringToEnumType = @{ @"enumTypeA" : @(XXEnumTypeA), @"enumTypeB" : @(XXEnumTypeB), @"enumTypeC" : @(XXEnumTypeC), }; ... self.enumType = [self.mapNSStringToEnumType[stringFromJSON] integerValue]; 

Now I want to go the other way to convert the enum value to a string. I don’t want to store another dictionary with reverse mapping, and the solution I use includes a linear search through the matching dictionary to find the value and then return the key.

In practice, my linear method is good, and neither performance nor memory is a problem, but I'm curious from a scientific point of view if there is another more efficient way that I don’t know about, or perhaps another type of structure that contains a mapping in both directions (so that all values ​​are unique)?

+4
source share
2 answers

You might want to try something on these lines:

 #define S(x) #x #define TOS(x) @S(x) 

and then:

 typedef enum { MyEnum_01 , MyEnum_02 } MyEnum ; - (void) test { NSLog(@"%@", TOS(MyEnum_01)) ; NSLog(@"%@", TOS(MyEnum_02)) ; } 
+1
source

Vocabulary objects are usually implemented either using BST (Binary Search Tree) or a Hash Table . Both of these data structures are designed to efficiently find values ​​from a key. If you read the description of these algorithms, you will understand why this is so. The best way to implement effective bidirectional searches is likely to be to implement a data structure that is supported by two dictionaries with key / value exchange types. There is a trade-off between space and time, which is probably inevitable.

0
source

Source: https://habr.com/ru/post/1495626/


All Articles