views:

199

answers:

1

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.

+2  A: 

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"];
e.James