Convert a NSString into the name of a Constant
I have a bunch of constants declared like this:
#define kConstant0 @"Cow"
#define kConstant1 @"Horse"
#define kConstant2 @"Zebra"
Elsewhere in code I'm trying to extract the constant value by adding an integer to the string name of the constant:
int myInt = 1; // (Actual intValue Pulled From Elsewhere)
myLabel.text = [@"kConstant" stringByAppendingString:[NSString stringWithFormat:@"%i",myInt]];
But of course this returns:
myLabel.text = @"kConstant1";
When I want it to return:
myLabel.text = @"Hors开发者_运维知识库e";
I can't figure out how to convert the NSString @"kConstant1" into the constant name kConstant1.
Any help is appreciated. lq
The answer is to avoid #defines for defining constants altogether. Use a NSString
constant like this instead:
NSString * const constant1 = @"Cow";
The big benefit is that now the constant has a type and is much better with regard to type safety.
You can't do it automatically. You have to store the mapping in an NSDictionary, e.g.
@implementation MyClass
static NSDictionary* constants;
+(void)initialize {
constants = [[NSDictionary alloc] initWithObjectsAndKeys:
@"kConstant0", @"Cow",
@"kConstant1", @"Horse", ...,
nil];
}
...
NSString* constantName = [kConstant stringByAppendingString:...];
myLabel.text = [constants objectForKey:constantName];
If all those constants are of the form kConstantN
, it is better to just create an array.
static NSString* kConstants[] = {@"Cow", @"Horse", @"Zebra", ...};
...
myLabel.text = kConstants[i];
精彩评论