Sno*_*man 7 random objective-c
我有一个14字符串的数组.我想向用户显示这14个字符串中的每一个而不重复.我得到的最接近的是创建一个整数数组并对它们的值进行混洗,然后使用int数组中的一个数字作为索引从字符串数组中读取:
//appDelegate.randomRiddles is an array of integers that has integer values randomly
appDelegate.randomRiddlesCounter++;
NSNumber *index=[appDelegate.randomRiddles objectAtIndex:appDelegate.randomRiddlesCounter];
int i = [index intValue];
while(i>[appDelegate.currentRiddlesContent count]){
appDelegate.randomRiddlesCounter++;
index=[appDelegate.randomRiddles objectAtIndex:appDelegate.randomRiddlesCounter];
i = [index intValue];
}
hintText.text = [[appDelegate.currentRiddlesContent objectAtIndex:i] objectForKey:@"hint"];
questionText.text = [[appDelegate.currentRiddlesContent objectAtIndex:i] objectForKey:@"question"];
Run Code Online (Sandbox Code Playgroud)
但我的方式是导致崩溃和重复.哦,每次我从字符串数组中读取一个值时,该字符串将从数组中删除,使其计数减少1.这样会使这一点复杂化.
像这样获取数组中的元素:
int position = arc4random() % ([myArray count]);
Run Code Online (Sandbox Code Playgroud)
这种方式即使count减1,也没关系,因为你仍然会得到一个有效的下一个位置值,直到没有任何更多的可能值.