开发者

How to serialise ObjC enums in JSON?

开发者 https://www.devze.com 2022-12-21 17:28 出处:网络
I would like to store my app\'s skin settings in a json file. How would I go about storing the enum values for colours/styles etc and then cast them back from a string?How would I store MKPinAnnotatio

I would like to store my app's skin settings in a json file. How would I go about storing the enum values for colours/styles etc and then cast them back from a string? How would I store MKPinAnnotationColorRed or UITableViewStyleGroupe开发者_JAVA技巧d?

If it's just a matter of storing the integer equivalent I'm fine with that, rather than actually storing the enum string value.


The short answer is, you can't.

Unless you do one of a couple things:

  1. Store the integer value of the enum in the json file. (this is your "If its just a matter of storing the integer equivilent Im fine with that rather than actually storing the enum string value", which seems like the simplest, best solution).
  2. Keep a seperate array of enum values as strings and compare against them and return the index of the correct entry.
  3. Instead of using an enum, use string constants.
  4. Instead of an enum use four-character constants which can be parsed as either an integer or a string.


"I would like to store my apps skin settings in a json file" - This is the wrong approach on the iPhone. The OS provides the NSUserDefaults class that handles all the details for you.

For example, to store an enum value (which are really integer values):

[[NSUserDefaults standardUserDefaults] setInteger: annotationColor
    forKey: @"SomeKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

You can also easily store and retrieve serialized objects or native types (arrays, dicts, numbers, strings).


You have to create some explicit mapping between enums and strings. One approach would be the following:

#define ENTRY(x) [NSNumber numberWithInt:x], @#x

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
    ENTRY(enumOne),
    ENTRY(enumTwo),
    ENTRY(enumThree),
    nil];

#undef ENTRY

NSNumber* index = [dict objectForKey:@"enumOne"]);

Note that this is the generic approach, if you have enumeration values who are equidistant, you don't have to store their numeric value and could use e.g. an NSArray instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号