将 NSString 转换为常量的名称
我有一堆这样声明的常量:
#define kConstant0 @"Cow"
#define kConstant1 @"Horse"
#define kConstant2 @"Zebra"
在代码的其他地方,我试图通过向常量的字符串名称添加一个整数来提取常量值:
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。
任何帮助表示赞赏。 lq
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能自动完成它。您必须将映射存储在 NSDictionary 中,例如,
如果所有这些常量都是 kConstantN 形式,那么最好只创建一个数组。
You can't do it automatically. You have to store the mapping in an NSDictionary, e.g.
If all those constants are of the form
kConstantN
, it is better to just create an array.答案是完全避免使用 #defines 来定义常量。使用像这样的
NSString
常量:最大的好处是现在常量有一个类型,并且在类型安全方面要好得多。
The answer is to avoid #defines for defining constants altogether. Use a
NSString
constant like this instead:The big benefit is that now the constant has a type and is much better with regard to type safety.