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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With