Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Token for using enum data type using NSLog

I am trying to display the value stored a particular value of enum using NSLog. In the following example, I am trying to get the output as: 5 represents month of May.

Any idea what is the right token to use for enum with NSLog? I tried using %i and %@, but both do not work.

Thanks!

enum month {jan = 1, feb, march, apr, may, jun, jul, aug, sep, oct, nov, dec};
enum month amonth;
int x = 5;
amonth = x;
NSLog(@"%i represents month of %@", x,amonth);
like image 742
Rutvij Kotecha Avatar asked Aug 17 '12 20:08

Rutvij Kotecha


1 Answers

Unfortunately, what you're asking for is not possible. Enum names are not preserved past compilation (except as debugging information available to the compiler). So unless you want to a) ship debugging information in your app, and b) effectively write a debugger inside your app that uses the embedded debugging information, it's just not going to work.

The typical solution to this problem is to provide a function that returns the appropriate name, using a switch statement.

NSString *monthName(enum month m) {
    switch (m) {
        case jan:
            return @"jan";
        case feb:
            return @"feb";
        ...
    }
    return @"unknown";
}

One benefit of this approach is you can localize the names.

like image 193
Lily Ballard Avatar answered Sep 30 '22 14:09

Lily Ballard