Make variable name from NSString
I have a for loop where I need to create 9 hexagons (hexagon1 through hexagon9) ... But I can't use hexString as the Sprite name because it's an NSString, right? So how can I get 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);
}
source to share
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 rewriting hexString
which you assign here:
NSString *hexString = [NSString stringWithFormat:@"hexagon%d",i];
With help here:
hexString = [self createHexagon:ccp(xVal,yVal) : i];
And this method call is an obvious syntax error with a dangling part : i
.
source to share