显示随机单词和用户名

时间:2012-06-10 15:14:33

标签: iphone objective-c ios xcode

为什么这不起作用?

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;        }
}

尝试使用不同的设置,但是无法正常工作

3 个答案:

答案 0 :(得分:5)

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

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

(有关逗号如何在C中运行的更多信息:http://en.wikipedia.org/wiki/Comma_operator。我相信在这种情况下,您将text设置为username然后进行评估,但不会使用结果,@"LEOONS"。)

答案 1 :(得分: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()

的信息,请参阅this

答案 2 :(得分: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]];