且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何连续获取两次相同的数组值

更新时间:2023-02-05 19:30:52

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

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