Skip to content

Instantly share code, notes, and snippets.

@BenedictC
Created December 9, 2012 20:03
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BenedictC/4246759 to your computer and use it in GitHub Desktop.
Save BenedictC/4246759 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(int 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] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; \
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:@"%i 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 "EMKArfValue3"
}
return 0;
}
@Daij-Djan
Copy link

id make part of the long macro into a function (it can be inlined if that matters)

so that e.g. EMKArfnoidToString only calls EMKEnumValueToString(allArfnoidEnumValues, enumValue);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment