Unpacking packed primitives (such as an enum) from NSArray or NSDictionary during fast enumeration

142 Views Asked by At

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? For example, something like:

for (MyEnum enum in dictionary) {
    ...
}

This results in the error Selector element type 'MyEnum' is not a valid object

1

There are 1 best solutions below

0
chibimagic On

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];
    ...
}