Recipe: Enums to Strings and vice versa

(UPDATE: There’s a newer, companion post to this: HERE )

I’ve been finding it annoying sometimes when I have enums but then am debugging something and of course in the console, it’s not very human readable when it says something like:

Log> <MyObject: 0x234b3a> id: 23 type: 4

What is type 4?? Exactly. So let’s get something more readable in there: Here’s how you can easily get between the two:

// In your .h file, outside of an @interface declaration

typedef enum : NSInteger {
  MoodUnknown = -1,
  MoodDefault = 0,
  MoodExcited,
  MoodAngry,
  MoodHappy,
  MoodLazy
}Mood;

extern NSString * const MoodTypes[];

// conversion methods
extern NSString* NSStringFromMood(Mood m);
extern Mood MoodFromNSString(NSString *key);

Now then…

// in your .m file, outside (above) your @implmentation
NSString * const MoodTypes[] = {
  @"MoodDefault",
  @"MoodExcited",
  @"MoodAngry",
  @"MoodHappy",
  @"MoodLazy"
};

// UPDATE: why this?  Because if you have more than one of these arrays defined, using sizeof(MoodTypes) won't be correct.
static NSInteger const MoodTypesCount = 5;  

NSString* NSStringFromMood(Mood m)
{
  // in case you define an unknown mood as -1
  if(m < 0)
  {
    return @"MoodUnknown";
  }

  return MoodTypes[m];
}

Mood MoodFromNSString(NSString *key)
{
  if ([key isEqualToString:@"MoodUnknown"]) {
        return MoodUnknown;
    }

    for (int i = 0; i < MoodTypesCount - 1; i++) {
        if ([(NSString*)MoodTypes[i] isEqualToString: key]) {
            return (Mood)i;
        }
    }
    return MoodUnknown;
}

Then in your code, you’d have something like:

NSLog(@"Printing Object of Type: %@", NSStringFromMood(object.mood));
Advertisements

One thought on “Recipe: Enums to Strings and vice versa

  1. Pingback: Recipe: NSString from an Enum | Thought Repository

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s