Chibimagic's Weblog

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

Posted on: February 20, 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: