如何连续获取两次相同的数组值 [英] How to get not twice the same array value in a row

查看:47
本文介绍了如何连续获取两次相同的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,当我按下一个按钮时,该代码会导致标签更改.我试图编写代码,以使标签不能连续两次获得相同的值,但是它却行不通,因为有时我仍然连续两次获得相同的值.

I have code that, when I press a button, causes the label to change. I'd tried to write code so that the label doesn't get the same value twice in a row, but it didn't work because I still get the same value in the twice in a row sometimes.

什么是正确的解决方案?

What is the right solution?

这是代码:

- (IBAction)buttonPressed:(id)sender {
    if (sender == self.button) {
        // Change the randomLabel by right answer
        NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
        words = [[NSMutableArray alloc] initWithContentsOfFile:path];
        NSString *generateRandomLabel = [NSString stringWithFormat:@"%@", [words objectAtIndex:arc4random_uniform([words count] - 1)]];

        if ([randomLabel.text isEqualToString:generateRandomLabel]) {
            while ([randomLabel.text isEqualToString:generateRandomLabel]) {
                generateRandomLabel = [NSString stringWithFormat:@"%@", [words objectAtIndex:arc4random_uniform([words count] - 1)]];
            }
        } else if (![randomLabel.text isEqualToString:generateRandomLabel]) {
            [self.randomLabel setText:generateRandomLabel];
            [randomLabel.text isEqualToString:generateRandomLabel];
        }
    }

推荐答案

您可以非常简单地执行此操作,方法是从数组的除最后一个之外的所有成员中选择随机数生成器,然后交换您选择的那个数组中的最后一项:

You can do this very simply by having your random number generator pick from all the members of the array except the last one, and then exchange the one you pick with the last item in the array:

- (IBAction)buttonPressed:(id)sender {
    if (! words) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
        words = [[NSMutableArray alloc] initWithContentsOfFile:path];
    }
    NSInteger index = arc4random_uniform(words.count - 2);
    randomLabel.text = words[index];
    [words exchangeObjectAtIndex:index withObjectAtIndex:words.count-1];
}

这篇关于如何连续获取两次相同的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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