0
typedef enum {
    red = 10,
    blue = 21,
    white = 32
} colors;
#define ENUMvalue2str(value)   @(#value)

I used ENUMvalue2str(white) get @"white", now, I want get white from @"white". not use NSArray, how to do it ?

Machavity
  • 30,841
  • 27
  • 92
  • 100
wxiubin
  • 13
  • 3
  • 1
    `I want get white from @"white"` <- this is not clear to me what you want to achieve. – Cœur Jun 02 '17 at 08:19
  • 1
    You may have answers on https://stackoverflow.com/questions/925991/objective-c-nsstring-to-enum or https://stackoverflow.com/questions/7083361/objective-c-convert-string-to-enum or https://stackoverflow.com/questions/16844728/converting-from-string-to-enum-in-c – Cœur Jun 02 '17 at 08:26

1 Answers1

0

enums are from pure C. There is no runtime information about the label strings. Therefore it is impossible to translate an instance of an NSString into a value of an enumeration label. The only way to do that is to have if cascades.

This is one reason, why I do not use C enumerations, if it is possible. I simply define strings for the label and pass the string itself as argument, if the enum value is simply a marker, an option. If I need a combination of values (aka bit sets) I use instances of NSSet with strings.

If your are interested in a specific value of an enumeration (instead of having simply 0, 1, 2, …), you can use dictionaries as explained in the link in the comment to your Q.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50