问题描述
我有一个 for 循环,其中必须创建 9 个六边形(hexagon1 到 hexagon9)...但是我不能使用 hexString 作为 Sprite 的名称,因为它是一个 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 [<- 我希望 for 循环生成hexagon1",然后是hexagon2"等等,而不是 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);
}
推荐答案
使用 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];
}
顺便说一句,你为什么要覆盖你在这里分配的 hexString
:
By the way, why are you overwriting hexString
that you assign here:
NSString *hexString = [NSString stringWithFormat:@"hexagon%d",i];
这里有一个:
hexString = [self createHexagon:ccp(xVal,yVal) : i];
并且该方法调用是一个明显的语法错误,其中悬挂 : i
部分.
And that method call is an obvious syntax error with the dangling : i
part there.
这篇关于使用 NSString 制作变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!