Chibimagic's Weblog

Archive for February 2015

You can put primitives in an NSArray or NSDictionary by packing them with the @() syntax. For example:

typedef enum {
    MyEnumOne,
    MyEnumTwo
} MyEnum

NSDictionary *dictionary = @{
                             @(MyEnumOne) : @"one",
                             @(MyEnumTwo) : @"two"
                             };

But how do you then use this with fast enumeration? Turns out, the @() syntax creates a boxed NSNumber. Therefore, when enumerating, access it as an NSNumber. To cast it back to an enum, first extract the integer value, then cast:

for (NSNumber *number in dictionary) {
    MyEnum myEnum = (MyEnum)[number intValue];
    ...
}
Advertisements