Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving enum values into a dictionary

Tags:

How does one save an enum value to a dictionary?

When I try the following

enum someEnum
{
    field0 = 0,
    field1 = 1,
    field2 = 2,
};

enum someEnum someEnumObject;

and I try to save it to a dictionary using

[NSDictionary dictionaryWithObjectsAndKeys:]

someEnumObject, @"enum", 

I get this

warning: Semantic Issue: Incompatible integer to pointer conversion sending 'enum behaviour' to parameter of type 'id'

like image 484
user773578 Avatar asked Jul 12 '11 11:07

user773578


2 Answers

Use the following to save it to dictionary,

[NSNumber numberWithInt:enumValue], @"enum",

And you can retrieve it as,

enumValue = [[dictionary valueForKey:@"enum"] intValue];
like image 128
EmptyStack Avatar answered Oct 04 '22 10:10

EmptyStack


Better use NSNumber literals to convert an enum to an object so that it can be stored in NSDictionary:

[NSDictionary dictionaryWithObjectsAndKeys:@(someEnumObject), @"enum", nil];

Literals provide shorthands to write stuff, this dictionary can be written like:

@{@"enum":@(someEnumObject)};

Read more about literals here: http://clang.llvm.org/docs/ObjectiveCLiterals.html

like image 31
jarora Avatar answered Oct 04 '22 12:10

jarora