views:

276

answers:

3

I would like to store my apps skin settings in a json file, how would I go about storing the enum values for colours/styles etc and cast them back from a string.

e.g how do I store MKPinAnnotationColorRed or UITableViewStyleGrouped

If its just a matter of storing the integer equivilent Im fine with that rather than actually storing the enum string value

+3  A: 

"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).

St3fan
OK so my explanation was a little thin the reason I am storing it in json is that the skin is actually defined via a webservice
tigermain
How do I cast it back though is my question?
tigermain
+1  A: 

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.
Ed Marty
+1  A: 

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.

Georg Fritzsche