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];
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With