将NSString转换为常量的名称 [英] Convert a NSString into the name of a Constant

查看:72
本文介绍了将NSString转换为常量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆这样声明的常量:

I have a bunch of constants declared like this:

#define kConstant0  @"Cow"
#define kConstant1  @"Horse"
#define kConstant2  @"Zebra"

在代码I'的其他位置m尝试通过在常量的字符串名称中添加整数来提取常量值:

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

当然,这会返回:

myLabel.text = @"kConstant1";

当我要返回时:

myLabel.text = @"Horse";

我不知道如何将NSString @ kConstant1转换为常数kConstant1。

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

感谢您的帮助。
lq

Any help is appreciated. lq

推荐答案

您无法自动执行此操作。您必须将映射存储在NSDictionary中,例如

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

如果所有这些常量的形式均为 kConstantN ,最好只创建一个数组。

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

这篇关于将NSString转换为常量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆