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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

Advertisements

  • optical franchise opportunities: Right now it looks like Wordpress is the preferred blogging platform out there right now. (from what I've read) Is that what you are using on your blo
  • startup speaker: Interesting content. A magnificent article. It is very informative and you are obviously very knowledgeable in this area.
  • Jesse Grillo Jesse Grillo: You have brought up a very superb points I will bookmark this. it is like you wrote the book on it or something.

Categories

%d bloggers like this: