If I have the following enum:
typedef enum _colors {
RED,
GREEN,
BLUE
} MyColors;
How can I convert an enum value of MyColors type to an NSString, i.e.:
MyColors color = RED;
NSString *colorString = ?;
Thanks,
Brad
You need to write a translation method. Just do a case statement on
the values that returns the string you need.
As Saul mentioned, the enum is always some sort of integer. The
compiler infers the type (unsigned, signed, long long) for you. Due
to this, I'd recommend being explicit about your definitions. It's
not really much more work to do and can save you a debugging headache
for a couple edge cases that can crop up when moving from 32-bit to 64-
bit. We're not their yet, but it's not hard to imagine a 64-bit chip
in the iphone in a few years.
type enum {
RED = 0,
GREEN = 1,
BLUE = 2
}
typedef NSUInteger MyColors
I also recommend setting the value over letting the compiler set them
for you. It's a bit safer and more portable. It probably won't
happen, but the compiler could always decide to change the way it
assigns values, say starting at 1 instead of 0. If you're storing
values in preferences or something, they'll then be off if a change
ever did happen. You might also end up working on some platform that
has an oddball compiler that starts at max int and works backwards or
something. If cross platform documents get created, you're going to
have issues. So it's probably not a huge problem, but I feel it's
better to be explicit and safe where ever I can.
Brad Miller
br...@cynicalpeak.com
http://cynicalpeak.com/