Getting random objects from an array, and if the objects are the same, get a new object.
Posted
by
XcodeDev
on Stack Overflow
See other posts from Stack Overflow
or by XcodeDev
Published on 2011-02-07T23:05:57Z
Indexed on
2011/02/07
23:25 UTC
Read the original article
Hit count: 277
Hi,
I have made a jokes application, where the user generates a joke and the joke will display in a UILabel. However I am trying to randomise the jokes show, but I do not want to show the same joke twice. Please could you tell me how I could do this. I am using the code below to try and do that, but it seems that it is not working.
- (IBAction)generateNewJoke {
if (i < [jokeArray count]) {
i++;
[userDefaults setInteger:[userDefaults integerForKey:kNewIndex] forKey:kOldIndex];
int oldnumber = [userDefaults integerForKey:kOldIndex];
int newnumber = [userDefaults integerForKey:kNewIndex];
[answerLabel setText:@""];
[userDefaults setInteger:i forKey:kNewIndex];
if (oldnumber == newnumber) {
NSLog(@"they are the same");
[userDefaults setInteger:arc4random()%[jokeArray count] forKey:kNewIndex];
}
[jokeLabel setText:[jokeArray objectAtIndex:[userDefaults integerForKey:kNewIndex]]];
}
}
© Stack Overflow or respective owner