1

我正在制作一个有很多常量的程序。我决定将它们全部放入一个单独的类中,并通过需要它的类来导入它。这些文件看起来与此类似

// 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 语句来访问正确的变量会更好。有谁知道这样做的方法?提前致谢。

4

1 回答 1

3

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

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

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

int baseCost = [myClass buildingCostForKey:@"base"];
于 2009-08-08T03:03:59.727 回答