在 Objective-C 中使用键值编码访问常量
我正在编写一个有很多常量的程序。 我决定将它们全部放入一个单独的类中,并由需要它的类导入它。 这些文件看起来与此类似,
// Constants.h
extern const int baseCostForBuilding;
extern const int maxCostForBuilding;
// etc
// Constants.m
const int baseCostForBuilding = 400;
const int maxCostForBuilding = 1000;
// etc
我想做的是使用键值编码访问它们。 到目前为止我所尝试的方法还没有奏效。
id object = [self valueForKey:@"baseCostForBuilding"];
但我可以执行以下操作并且效果很好。
id object = baseCostForBuilding;
这可能看起来毫无意义,但我有很多变量必须以“CostForBuilding”结尾,而我需要它的函数仅获取字符串的第一部分。 例如,“base”、“max”、“intermediate”等。然后它将与“CostForBuilding”或其他内容组合以获取变量名称。
如果可能的话,最好只用一两行代码而不是多个 if 语句来访问正确的变量。 有谁知道如何做到这一点? 提前致谢。
I'm making a program that has a lot of constants. I decided to put them all into a separate class and I'm importing it by the classes that need it. The files look similar to this
// Constants.h
extern const int baseCostForBuilding;
extern const int maxCostForBuilding;
// etc
// Constants.m
const int baseCostForBuilding = 400;
const int maxCostForBuilding = 1000;
// etc
What I'm trying to do is access them using key-value coding. What I've tried so far hasn't worked.
id object = [self valueForKey:@"baseCostForBuilding"];
But I can do the following and it works fine.
id object = baseCostForBuilding;
This may seem pointless but I have a lot of variables that have to end in "CostForBuilding" and the function I need this in only gets the first part of the string. Example, "base", "max", "intermediate", etc. It will then combine it with "CostForBuilding" or something else to get the variable name.
If this is possible, it would be way nicer to only have one or two lines of code instead of multiple if-statements to access the correct variable. Does anyone know a way to do this? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用适当的值填充字典:
然后可以按如下方式使用:
You can fill a dictionary with the appropriate values:
Which you could then use as follows: