0

为什么这不起作用?

NSString *username = [[GKLocalPlayer localPlayer] alias];

random(); { 
    int text = rand() % 4;
    switch (text) {
        case 0: mainTextController.text = username,@"LEOONS"; break;
        case 1: mainTextController.text = username,@"AAIING"; break;
        case 2: mainTextController.text = username,@"AALBES"; break;
        case 3: mainTextController.text = username,@"AALDIJK"; break;


        default:
        break;        }
}

尝试了不同的设置,但不起作用

4

3 回答 3

5

问题是mainTextController.text = username,@"LEOONS";。逗号不连接 Objective-C 字符串对象(也不是 C 字符串,为了记录)。你的意思是:

mainTextController.text = [username stringByAppendingString:@"LEOONS"];

(有关逗号在 C 中如何工作的更多信息:http ://en.wikipedia.org/wiki/Comma_o​​perator 。我相信在这种情况下,您正在设置textusername然后评估,但不使用,的结果@"LEOONS"。)

于 2012-06-10T15:18:07.823 回答
3

正如andyvn22 所说,您需要使用-stringByAppendingString:连接两个字符串。我想补充一点,您的问题可以像这样更好地解决:

NSString *username = [[GKLocalPlayer localPlayer] alias];
NSArray *randomAddons = [NSArray arrayWithObjects:
                         @"LEOONS",
                         @"AAIING",
                         @"AALBES"
                         /* Add as many as you want here.... */, nil];
int randomIndex = arc4random() % [randomAddons count];
mainTextController.text = [username stringByAppendingString:[randomAddons objectAtIndex:randomIndex]];

(有关信息,请参阅此处arc4random()

于 2012-06-10T15:24:25.190 回答
2

也许你想要更随机和更有未来的证据:-)

NSString *username = [[GKLocalPlayer localPlayer] alias];
int text = arc4random_uniform(4); //Don't do this: rand() % val or arc4random() % val
switch (text) {
    case 0: mainTextController.text = [NSString stringWithFormat:@"%@ %@ ",username,@"LEOONS"]; break;
    case 1: mainTextController.text = [NSString stringWithFormat:@"%@ %@ ",username,@"AAIING"]; break;
    case 2: mainTextController.text = [NSString stringWithFormat:@"%@ %@ ",username,@"AALBES"]; break;
    case 3: mainTextController.text = [NSString stringWithFormat:@"%@ %@ ",username,@"AALDIJK"]; break;
    default:
        break;
}

但更好的是:

NSMutableArray* names = [[NSMutableArray alloc] init];
[names addObject:@"LEOONS"];
[names addObject:@"AAIING"];
[names addObject:@"AALBES"];
[names addObject:@"AALDIJK"];

NSString *username = [[GKLocalPlayer localPlayer] alias];
int text = arc4random_uniform([names count]); //again use arc4random_uniform
mainTextController.text = [NSString stringWithFormat:@"%@ %@ ",username,[names objectAtIndex:text]];
于 2012-06-10T15:26:12.113 回答