Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa: Dictionary with enum keys?

Tags:

I need to create a dictionary/hashmap where the

  • Keys are enums
  • Values are some subclass of NSObject

NSDictionary won't work here (enums don't conform to NSCopying).

I could perhaps use a CFDictionaryRef here, but I'd like to know if is there any other way to achieve this.

like image 541
Debajit Avatar asked Jul 27 '09 08:07

Debajit


1 Answers

Since enums are integers, you can wrap the enum in an NSNumber. When you add/retreive something to/from the map, you pass the enum to the NSNumber constructor...

Assuming you've got an enum like...

enum ETest {     FOO, BAR }; 

You can use it in an NSDictionary like this...

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setObject: @"Foo!" forKey:[NSNumber numberWithInt: FOO]]; NSLog(@"getting value for FOO -> %@",        [dict objectForKey: [NSNumber numberWithInt: FOO]]);   [dict release];  
like image 105
VoidPointer Avatar answered Oct 04 '22 02:10

VoidPointer