Convert a NSString into the name of a Constant

半世苍凉 提交于 2019-12-24 08:23:28

问题


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 = @"Horse";

I can't figure out how to convert the NSString @"kConstant1" into the constant name kConstant1.

Any help is appreciated. lq


回答1:


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];



回答2:


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.



来源:https://stackoverflow.com/questions/5542835/convert-a-nsstring-into-the-name-of-a-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!