tags:

views:

301

answers:

2

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];
+3  A: 

No, you can't. Look at the method signature: id specifies an object. An enum type is a scalar. You can't cast from one to the other and expect it to work right. You have to use an object.

Chuck
This is true. However, you could wrap the enum value in an NSNumber and use that as the key.
LBushkin
+4  A: 

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];
Bridgeyman