Saving enum values into a dictionary

怎甘沉沦 提交于 2019-11-30 11:57:23

问题


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'


回答1:


Use the following to save it to dictionary,

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

And you can retrieve it as,

enumValue = [[dictionary valueForKey:@"enum"] intValue];



回答2:


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




回答3:


An enum is essentially an integer and an NSDictionary stores objects, so you need to convert your enum to an object. An NSNumber would work well for this:

[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:someEnumObject], @"enum", nil];



回答4:


In modern times @(enumValue) is the easier approach.



来源:https://stackoverflow.com/questions/6663686/saving-enum-values-into-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!