到 OP。要使随机答案不重复,请将您的数组设置为视图控制器的 viewDidLoad 中的实例变量。还要创建一个属性剩余单词:
@property (nonatomic, 保留) NSMutableArray *remainingWords;
您的 viewDidLoad 代码如下所示:
-(void) viewDidLoad;
{
//Create your original array of words.
self.words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ];
//Create a mutable copy so you can remove words after choosing them.
self.remainingWords = [self.words mutableCopy];
}
然后你可以写一个这样的方法来从你的数组中获取一个唯一的单词:
- (NSString *) randomWord;
{
//This code will reset the array and start over fetching another set of unique words.
if ([remainingWords count] == 0)
self.remainingWords = [self.words MutableCopy];
//alternately use this code:
if ([remainingWords count] == 0)
return @""; //No more words; return a blank.
NSUInteger index = arc4random_uniform([[remainingWords count])
NSString *result = [[[remainingWords index] retain] autorelease];
[remainingWords removeObjectAtindex: index]; //remove the word from the array.
}