Accessing constants using Key-Value Coding in Objective-C

眉间皱痕 提交于 2019-12-13 19:22:16

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/1247832/accessing-constants-using-key-value-coding-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!