enum Values to NSString (iOS)

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

    Here is a plug-and-play solution that you can extend with a simple copy and paste of your EXISTING definitions.

    I hope you all find it useful, as I have found useful so many other StackOverflow solutions.

    - (NSString*) enumItemNameForPrefix:(NSString*)enumPrefix item:(int)enumItem {
    NSString* enumList = nil;
    if ([enumPrefix isEqualToString:@"[Add Your Enum Name Here"]) {
        // Instructions:
        // 1) leave all code as is (it's good reference and won't conflict)
        // 2) add your own enums below as follows:
        //    2.1) duplicate the LAST else block below and add as many enums as you like
        //    2.2) Copy then Paste your list, including carraige returns
        //    2.3) add a back slash at the end of each line to concatenate the broken string
        // 3) your are done.
    }
    else if ([enumPrefix isEqualToString:@"ExampleNonExplicitType"]) {
        enumList = @" \
        ExampleNonExplicitTypeNEItemName1, \
        ExampleNonExplicitTypeNEItemName2, \
        ExampleNonExplicitTypeNEItemName3 \
        ";
    }
    else if ([enumPrefix isEqualToString:@"ExampleExplicitAssignsType"]) {
        enumList = @" \
        ExampleExplicitAssignsTypeEAItemName1 = 1, \
        ExampleExplicitAssignsTypeEAItemName2 = 2, \
        ExampleExplicitAssignsTypeEAItemName3 = 4 \
        ";
    }
    else if ([enumPrefix isEqualToString:@"[Duplicate and Add Your Enum Name Here #1"]) {
        // Instructions:
        // 1) duplicate this else block and add as many enums as you like
        // 2) Paste your list, including carraige returns
        // 3) add a back slash at the end of each line to continue/concatenate the broken string
        enumList = @" \
        [Replace only this line: Paste your Enum Definition List Here] \
        ";
    }
    
    // parse it
    int implicitIndex = 0;
    NSString* itemKey = nil;
    NSString* itemValue = nil;
    NSArray* enumArray = [enumList componentsSeparatedByString:@","];
    NSMutableDictionary* enumDict = [[[NSMutableDictionary alloc] initWithCapacity:enumArray.count] autorelease];
    
    for (NSString* itemPair in enumArray) {
        NSArray* itemPairArray = [itemPair componentsSeparatedByString:@"="];
        itemValue = [[itemPairArray objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        itemKey = [NSString stringWithFormat:@"%d", implicitIndex];
        if (itemPairArray.count > 1)
            itemKey = [[itemPairArray lastObject] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        [enumDict setValue:itemValue forKey:itemKey];
        implicitIndex++;
    }
    
    // return value with or without prefix
    NSString* withPrefix = [enumDict valueForKey:[NSString stringWithFormat:@"%d", enumItem]];
    NSString* withoutPrefix = [withPrefix stringByReplacingOccurrencesOfString:enumPrefix withString:@""];
    NSString* outValue = (0 ? withPrefix : withoutPrefix);
    if (0) NSLog(@"enum:%@ item:%d retVal:%@ dict:%@", enumPrefix, enumItem, outValue, enumDict);
    return outValue;
    }
    

    Here are the example declarations:

    typedef enum _type1 {
    ExampleNonExplicitTypeNEItemName1, 
    ExampleNonExplicitTypeNEItemName2, 
    ExampleNonExplicitTypeNEItemName3
    } ExampleNonExplicitType;
    
    typedef enum _type2 {
    ExampleExplicitAssignsTypeEAItemName1 = 1, 
    ExampleExplicitAssignsTypeEAItemName2 = 2, 
    ExampleExplicitAssignsTypeEAItemName3 = 4
    } ExampleExplicitAssignsType;
    

    Here is an example call:

    NSLog(@"EXAMPLE:  type1:%@  type2:%@ ", [self enumItemNameForPrefix:@"ExampleNonExplicitType" item:ExampleNonExplicitTypeNEItemName2], [self enumItemNameForPrefix:@"ExampleExplicitAssignsType" item:ExampleExplicitAssignsTypeEAItemName3]);
    

    Enjoy! ;-)

    0 讨论(0)
  • 2020-12-04 08:13

    Here is working code https://github.com/ndpiparava/ObjcEnumString

    //1st Approach
    #define enumString(arg) (@""#arg)
    
    //2nd Approach
    
    +(NSString *)secondApproach_convertEnumToString:(StudentProgressReport)status {
    
        char *str = calloc(sizeof(kgood)+1, sizeof(char));
        int  goodsASInteger = NSSwapInt((unsigned int)kgood);
        memcpy(str, (const void*)&goodsASInteger, sizeof(goodsASInteger));
        NSLog(@"%s", str);
        NSString *enumString = [NSString stringWithUTF8String:str];
        free(str);
    
        return enumString;
    }
    
    //Third Approcah to enum to string
    NSString *const kNitin = @"Nitin";
    NSString *const kSara = @"Sara";
    
    
    typedef NS_ENUM(NSUInteger, Name) {
        NameNitin,
        NameSara,
    };
    
    + (NSString *)thirdApproach_convertEnumToString :(Name)weekday {
    
        __strong NSString **pointer = (NSString **)&kNitin;
        pointer +=weekday;
        return *pointer;
    }
    
    0 讨论(0)
  • 2020-12-04 08:17

    I will introduce is the way I use, and it looks better than previous answer.(I thinks)

    I would like to illustrate with UIImageOrientation for easy understanding.

    typedef enum {
        UIImageOrientationUp = 0,            // default orientation, set to 0 so that it always starts from 0
        UIImageOrientationDown,          // 180 deg rotation
        UIImageOrientationLeft,          // 90 deg CCW
        UIImageOrientationRight,         // 90 deg CW
        UIImageOrientationUpMirrored,    // as above but image mirrored along other axis. horizontal flip
        UIImageOrientationDownMirrored,  // horizontal flip
        UIImageOrientationLeftMirrored,  // vertical flip
        UIImageOrientationRightMirrored, // vertical flip
    } UIImageOrientation;
    

    create a method like:

    NSString *stringWithUIImageOrientation(UIImageOrientation input) {
        NSArray *arr = @[
        @"UIImageOrientationUp",            // default orientation
        @"UIImageOrientationDown",          // 180 deg rotation
        @"UIImageOrientationLeft",          // 90 deg CCW
        @"UIImageOrientationRight",         // 90 deg CW
        @"UIImageOrientationUpMirrored",    // as above but image mirrored along other axis. horizontal flip
        @"UIImageOrientationDownMirrored",  // horizontal flip
        @"UIImageOrientationLeftMirrored",  // vertical flip
        @"UIImageOrientationRightMirrored", // vertical flip
        ];
        return (NSString *)[arr objectAtIndex:input];
    }
    

    All you have to do is :

    1. name your function.

    2. copy contents of enum and paste that between NSArray *arr = @[ and ]; return (NSString *)[arr objectAtIndex:input];

    3. put some @ , " , and comma

    4. PROFIT!!!!

    0 讨论(0)
  • 2020-12-04 08:17

    This will be validated by compiler, so you won't mix up indices accidentally.

    NSDictionary *stateStrings =
     @{
       @(MCSessionStateNotConnected) : @"MCSessionStateNotConnected",
       @(MCSessionStateConnecting) : @"MCSessionStateConnecting",
       @(MCSessionStateConnected) : @"MCSessionStateConnected",
      };
    NSString *stateString = [stateStrings objectForKey:@(state)];
    

    var stateStrings: [MCSessionState: String] = [
        MCSessionState.NotConnected : "MCSessionState.NotConnected",
        MCSessionState.Connecting : "MCSessionState.Connecting",
        MCSessionState.Connected : "MCSessionState.Connected"
    ]
    var stateString = stateStrings[MCSessionState.Connected]
    
    0 讨论(0)
  • 2020-12-04 08:19

    This is answered here: a few suggestions on implementation

    The bottom line is Objective-C is using a regular, old C enum, which is just a glorified set of integers.

    Given an enum like this:

    typedef enum { a, b, c } FirstThreeAlpha;
    

    Your method would look like this:

    - (NSString*) convertToString:(FirstThreeAlpha) whichAlpha {
        NSString *result = nil;
    
        switch(whichAlpha) {
            case a:
                result = @"a";
                break;
            case b:
                result = @"b";
                break;
            case c:
                result = @"c";
                break;
    
            default:
                result = @"unknown";
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-12-04 08:20

    I didn't like putting the enum on the heap, without providing a heap function for translation. Here's what I came up with:

    typedef enum {value1, value2, value3} myValue;
    #define myValueString(enum) [@[@"value1",@"value2",@"value3"] objectAtIndex:enum]
    

    This keeps the enum and string declarations close together for easy updating when needed.

    Now, anywhere in the code, you can use the enum/macro like this:

    myValue aVal = value2;
    NSLog(@"The enum value is '%@'.", myValueString(aVal));
    
    outputs: The enum value is 'value2'.
    

    To guarantee the element indexes, you can always explicitly declare the start(or all) enum values.

    enum {value1=0, value2=1, value3=2};
    
    0 讨论(0)
提交回复
热议问题