enum Values to NSString (iOS)

前端 未结 16 1945
悲&欢浪女
悲&欢浪女 2020-12-04 07:57

I have an enum holding several values:

enum {value1, value2, value3} myValue;

In a certain point in my app, I wish to check which value of

16条回答
  •  执念已碎
    2020-12-04 08:06

    The solution below uses the preprocessor's stringize operator, allowing for a more elegant solution. It lets you define the enum terms in just one place for greater resilience against typos.

    First, define your enum in the following way.

    #define ENUM_TABLE \
    X(ENUM_ONE),    \
    X(ENUM_TWO)    \
    
    #define X(a)    a
    typedef enum Foo {
        ENUM_TABLE
    } MyFooEnum;
    #undef X
    
    #define X(a)    @#a
    NSString * const enumAsString[] = {
        ENUM_TABLE
    };
    #undef X
    

    Now, use it in the following way:

    // Usage
    MyFooEnum t = ENUM_ONE;
    NSLog(@"Enum test - t is: %@", enumAsString[t]);
    
    t = ENUM_TWO;
    NSLog(@"Enum test - t is now: %@", enumAsString[t]);
    

    which outputs:

    2014-10-22 13:36:21.344 FooProg[367:60b] Enum test - t is: ENUM_ONE
    2014-10-22 13:36:21.344 FooProg[367:60b] Enum test - t is now: ENUM_TWO
    

    @pixel's answer pointed me in the right direction.

提交回复
热议问题