简体   繁体   English

将NSString转换为常量的名称

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

I can't figure out how to convert the NSString @"kConstant1" into the constant name kConstant1. 我不知道如何将NSString @“ kConstant1”转换为常量名称kConstant1。

Any help is appreciated. 任何帮助表示赞赏。 lq q

The answer is to avoid #defines for defining constants altogether. 答案是避免完全定义常量的#define。 Use a NSString constant like this instead: 使用NSString常量代替:

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, eg 您必须将映射存储在NSDictionary中,例如

@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. 如果所有这些常量的形式kConstantN ,则最好仅创建一个数组。

static NSString* kConstants[] = {@"Cow", @"Horse", @"Zebra", ...};
...

myLabel.text = kConstants[i];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM