在Objective-C中使用键值编码访问常量 [英] Accessing constants using Key-Value Coding in Objective-C

查看:107
本文介绍了在Objective-C中使用键值编码访问常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个包含很多常量的程序。我决定将它们全部放在一个单独的类中,然后按需要的类将其导入。这些文件看起来与此类似。

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;

这似乎毫无意义,但是我有很多变量必须以 CostForBuilding结尾,并且我需要的功能仅获取字符串的第一部分。例如, base, max, intermediate等。它将与 CostForBuilding或其他名称结合使用以获取变量名称。

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语句来访问正确的变量会更好。有人知道这样做的方法吗?

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.

推荐答案

您可以使用适当的值填充字典:

You can fill a dictionary with the appropriate values:

- (id)init
{
    ...
    buildingCosts = [[NSDictionary alloc] initWithObjectsAndKeys:
                      [NSNumber numberWithInt:100], @"base",
                      [NSNumber numberWithInt:200], @"max",
                      ...,
                     nil];
    ...
}

- (int)buildingCostForKey:(NSString *)key
{
    return [(NSNumber *)[buildingCosts objectForKey:key] intValue];
}

- (void)dealloc
{
    [buildingCosts release];
}

然后您可以使用以下方式:

Which you could then use as follows:

int baseCost = [myClass buildingCostForKey:@"base"];

这篇关于在Objective-C中使用键值编码访问常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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