enum Values to NSString (iOS)

前端 未结 16 1916
悲&欢浪女
悲&欢浪女 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:13

    If I can offer another solution that has the added benefit of type checking, warnings if you are missing an enum value in your conversion, readability, and brevity.

    For your given example: typedef enum { value1, value2, value3 } myValue; you can do this:

    NSString *NSStringFromMyValue(myValue type) {
        const char* c_str = 0;
    #define PROCESS_VAL(p) case(p): c_str = #p; break;
        switch(type) {
                PROCESS_VAL(value1);
                PROCESS_VAL(value2);
                PROCESS_VAL(value3);
        }
    #undef PROCESS_VAL
    
        return [NSString stringWithCString:c_str encoding:NSASCIIStringEncoding];
    }
    

    As a side note. It is a better approach to declare your enums as so:

    typedef NS_ENUM(NSInteger, MyValue) {
        Value1 = 0,
        Value2,
        Value3
    }
    

    With this you get type-safety (NSInteger in this case), you set the expected enum offset (= 0).

提交回复
热议问题