Skip to content

Instantly share code, notes, and snippets.

@Krishna
Forked from BenedictC/gist:4246759
Created December 10, 2012 00:09
Show Gist options
  • Save Krishna/4247608 to your computer and use it in GitHub Desktop.
Save Krishna/4247608 to your computer and use it in GitHub Desktop.
A marco for creating enums with values which can be logged (inspired by http://rentzsch.tumblr.com/post/37512716957/enum-nsstring and long train journey).
#define EMKStringableEnum(ENUM_NAME, ENUM_VALUES...) \
\
typedef enum { \
ENUM_VALUES \
} ENUM_NAME; \
\
\
\
static NSString * ENUM_NAME##ToString(long enumValue) { \
static NSString *enumDescription = @"" #ENUM_VALUES; \
/*parse the enum values into a dict*/\
static NSDictionary *enumsByValue = nil; \
if (enumsByValue == nil) { \
NSMutableDictionary *mutableEnumsByValue = [NSMutableDictionary dictionary]; \
NSArray *enumPairs = [enumDescription componentsSeparatedByString:@","]; \
\
NSInteger lastValue = 0-1; /*set to 1 before the default value for the first enum*/ \
for (NSString *enumPair in enumPairs) { \
NSArray *labelAndValue = [enumPair componentsSeparatedByString:@"="]; \
NSString *label = [labelAndValue objectAtIndex:0]; \
BOOL hasExplictValue = [labelAndValue count] > 1; \
NSInteger value = (hasExplictValue) ? [[labelAndValue objectAtIndex:1] integerValue] : lastValue + 1; \
\
[mutableEnumsByValue setObject:label forKey:[NSNumber numberWithInteger:value]]; \
\
lastValue = value; \
} \
\
enumsByValue = [mutableEnumsByValue copy]; \
} \
\
NSString *label = [enumsByValue objectForKey:[NSNumber numberWithInteger:enumValue]]; \
if (label != nil) return label; \
\
return [NSString stringWithFormat:@"%li not defined as a %s value", enumValue, #ENUM_NAME]; \
}
EMKStringableEnum(EMKArfnoid,
EMKArfValue1 = 2,
EMKArfValue2,
EMKArfValue3 = 400);
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
EMKArfnoid arf = EMKArfValue3;
NSLog(@"%@", EMKArfnoidToString(arf)); //This will log EMKArfValue2
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment