Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print string representation of an enum, NSLog

I am trying to NSLog some enums I have. For example this piece of code prints the integer representation of the enum, but I want it to output the actual string name, in this case MON. How can I do that?

#import <Foundation/Foundation.h>
int main(void)
{
    typedef enum {
        SUN,
        MON,
        TUES
    } DAYS;

  DAYS d = MON;
  NSLog(@"%@", d);
  return 0;
}
like image 861
Huang Avatar asked Feb 01 '13 17:02

Huang


2 Answers

The LLDB debugger will show the string identifiers. So instead of using NSLog you could use a breakpoint with a debugger command action ("p d" in your case) and set the breakpoint to automatically continue after evaluating.

You can configure a breakpoint by right-clicking on the blue marker.

like image 171
tom Avatar answered Nov 15 '22 04:11

tom


Not easily. The string identifier for an enum value is for the developer, but internally it's simply a value with a particular type (in your example, DAYS).

You could write a translation method, to return the name of the enum value, e.g

- (NSString*)nameForDay:(DAYS)day {
    switch (day) {
        case SUN:
            return @"SUN";
        break;
        case MON:
            return @"MON";
        break;
        case TUES:
            return @"TUES";
        break;
        default:
            return nil;
        break;
    };

    return nil;
}

It's a nasty way of doing it, as it's not wholly resilient to the enum values changing, but its a way to associate a string with an enum value.

like image 30
WDUK Avatar answered Nov 15 '22 03:11

WDUK