Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C - Using Enum identifiers as string [duplicate]

The enumeration below is used in several places in a BMI tool :

typedef NS_ENUM (NSInteger, BMIStatus) {
    Malnutrition = 1,
    Anorexia = 2,
    Thinness = 3,
    Normal = 4,
    Overweight = 5,
    Obesity = 6,
    Morbid = 7
};

Is there a trick to use "Malnutrition" as a string ? Considering I have an image named "Malnutrition.png" that I want to load with a classical ImageNamed, and without using an intermediary array storing [1] => @"Malnutrition" for example.

My idea would be to use a kind of [UIImage imageNamed:[NSString stringWithFormat:@"%e", Malnutrition]] where %e leads to the enum identifier instead of the associated value.

Thanks.

like image 565
Kleioz Avatar asked Aug 11 '14 12:08

Kleioz


1 Answers

Unfortunately this is just not possible using Objective-C. However, it is in Swift if you can use Swift instead.

This is historically handled in Apple's code with NSString constants. For example:

UIKIT_EXTERN NSString *const NSFontAttributeName NS_AVAILABLE_IOS(6_0);

If you need to map between the int value and the NSString value, you will need to write a mapping function.

Also, do make sure to prefix your enums and string constants!

like image 151
colinbrash Avatar answered Oct 31 '22 10:10

colinbrash