Objective-C - using Enum identifiers as a string

The following listing is used in several places in the 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 using "Malnutrition" as a string? Given that I have an image called "Malnutrition.png" that I want to load using the classic ImageNamed, and without using an intermediate 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 an enumeration identifier instead of an associated value.

Thanks.

+6
source share
2 answers

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

This has historically been handled in Apple code with NSString constants. For instance:

 UIKIT_EXTERN NSString *const NSFontAttributeName NS_AVAILABLE_IOS(6_0); 

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

In addition, be sure to specify the prefix of your enumerations and string constants!

+4
source

If you need a string for debugging purposes, add the - (NSString*) stringFromBMIStatus with a switch statement that returns different strings, and by default enter a numeric value for unexpected input.

If you need a string that gives you an NSImage name for each enumeration value, add the - (NSString*) imageNameFromBMIStatus , possibly returning zero for unexpected input.

0
source

Source: https://habr.com/ru/post/973652/


All Articles