the_critic
the_critic

Reputation: 12820

Make variable name out of NSString

I have got a for loop where 9 hexagons (hexagon1 through hexagon9) have to be created... But I cannot use hexString as the name of the Sprite because it is a NSString, right ? So how would I make it right ?

hexString [<- I want the for loop to generate "hexagon1", then "hexagon2" and so on instead of the NSString] = [self createHexagon:ccp(xVal,yVal) :i];

int hexCount = [[[itemPositions valueForKey:myString]valueForKey:@"hexposition"] count];

    for (int i=1;i<=hexCount;i++){
        NSString *hexString = [NSString stringWithFormat:@"hexagon%d",i];
        NSNumber *generatedXVal = [[[[itemPositions valueForKey: myString ]valueForKey:@"hexposition"] valueForKey: hexString]valueForKey: @"xVal"];
        int xVal = [generatedXVal integerValue];
        NSNumber *generatedYVal = [[[[itemPositions valueForKey: myString ]valueForKey:@"hexposition"] valueForKey: hexString ]valueForKey: @"yVal"];
        int yVal = [generatedYVal integerValue];

        hexString = [self createHexagon:ccp(xVal,yVal) : i];
        NSLog(@"%@", hexString);
    }

Upvotes: 1

Views: 671

Answers (3)

Lukman
Lukman

Reputation: 19164

Use NSMutableDictionary.

for (int i=1;i<=hexCount;i++){
    NSString *hexString = [NSString stringWithFormat:@"hexagon%d",i];
    CCSprite *sprite = [self doSomethingToGetSprite];

    [mutableDictionary setObject:sprite forKey:hexString];
}        

Later you can iterate over all the sprites in the dictionary using:

for (NSString *key in mutableDictionary) {
    CCSprite *sprite = [mutableDictionary objectForKey:key];
    [self doStuffWithSprite:sprite];
}

By the way, why are you overwriting hexString that you assign here:

NSString *hexString = [NSString stringWithFormat:@"hexagon%d",i];

With the one here:

hexString = [self createHexagon:ccp(xVal,yVal) : i];

And that method call is an obvious syntax error with the dangling : i part there.

Upvotes: 1

RolandasR
RolandasR

Reputation: 3046

can you use NSSelectorFromString?

Upvotes: 0

TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

That would be impossible as you didn't declare the variable. A work around for this would be using an NSArray and saving your data on to the array instead of making a list of variables.

Upvotes: 3

Related Questions