从NSString中创建变量名 [英] Make variable name out of NSString

查看:80
本文介绍了从NSString中创建变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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中创建变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆