24 NovConvert objective-c typedef enum to its string equivalent

It’s small wonder that there is no standard way to get enum string description.

This is a code snippet solves the problems the easiest way:

// In a header filetypedef enum {  JSON,  XML,  Atom,  RSS} FormatType;

NSString * const FormatType_toString[];              

// In a source fileNSString * const FormatType_toString[] =
{  @"JSON",  @"XML",  @"Atom",  @"RSS"};...// To convert enum
to string:NSString *str = FormatType_toString[theEnumValue];

If you change the enum don’t forget to change the array of descriptions.

Second way is to create a mapping table. It’s more expensive in both sense

(your brain time and processor time) so i prefer the first one.

  • http://www.blogger.com/profile/14084810652115756180 izeye

    Hi. I'm Johnny.

    I read your post and I have a question.

    Is there really no standard way to change enum to its name in Objective-C?

  • http://www.blogger.com/profile/10136059479406321000 Slava

    I don't know such one. Please share if you will find ;)

  • http://www.blogger.com/profile/01101225283688554770 crunchyt

    Thanks Slava. I found these helper functions useful too. I made them complement your approach…

    //! Converts enum to a string representation
    -(NSString*) FormatTypeEnumToString:(TriggerType)enumVal
    {
    return FormatType_toString[enumVal];
    }

    //! Converts string representation of enum to a string
    -(FormatType) FormatTypeStringToEnum:(NSString*)strVal
    {
    int retVal;
    for(int i=0; i < sizeof(FormatType_toString)-1; i++)
    {
    if([(NSString*)FormatType_toString[i] isEqual:strVal])
    {
    retVal = i;
    break;
    }
    }
    return retVal;
    }

  • http://www.blogger.com/profile/10136059479406321000 Slava

    Not really helps me.
    I've seen this sample on the http://stackoverflow.com

    thanks anyway.