Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef enum type as key to NSDictionary?

Tags:

objective-c

Are enums not allowed as keys for an NSMutableDictionary?

When I try to add to the dictionary via:

[self.allControllers setObject:aController forKey:myKeyType];

I get the error:

error: incompatible type for argument 2 of 'setObject:forKey:'

Typically, I use NSString as my key name which doesn't require a cast to 'id' but to make the error go away, I had do that. Is the casting the correct behavior here or are enums as keys a bad idea?

My enum is defined as:

typedef enum tagMyKeyType
{
  firstItemType = 1,
  secondItemType = 2
} MyKeyType;

And the dictionary is defined and properly allocated as such:

NSMutableDictionary *allControllers;

allControllers = [[NSMutableDictionary alloc] init];
like image 505
Robin Jamieson Avatar asked Jun 18 '09 18:06

Robin Jamieson


1 Answers

You can store the enum in an NSNumber though. (Aren't enums just ints?)

[allControllers setObject:aController forKey:[NSNumber numberWithInt: firstItemType]];

In Cocoa, const NSStrings are often used. In the .h you would declare something like:

NSString * const kMyTagFirstItemType;
NSString * const kMyTagSecondtItemType;

And in the .m file you would put

NSString * const kMyTagFirstItemType = @"kMyTagFirstItemType";
NSString * const kMyTagSecondtItemType = @"kMyTagSecondtItemType";

Then you can use it as a key in a dictionary.

[allControllers setObject:aController forKey:kMyTagFirstItemType];
like image 173
Bridger Maxwell Avatar answered Sep 24 '22 23:09

Bridger Maxwell