nmzik
nmzik

Reputation: 151

"Load" texts from Plist file and use it(Xcode)

I have 4 UIbuttons and one UILabel.I want to do 4 words (from plist file )random shown on 4 buttons(one button has one word) and one word shown on label(that have the same name of the word on the button). How can I do that?

Upvotes: 0

Views: 1049

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108159

Assuming that your plist is called words.plist and that you have an array of 4 UIButtons

NSString * path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
NSMutableArray * words = [NSMutableArray arrayWithContentsOfFile:path];

Now you have all the possible words in the words array. At this point we need 4 unique random indices, which basically means to take the starting 4 elements of the array after randomly shuffling it. We'll use the Fisher-Yates shuffle algorithm as suggested in this answer.

for (int i = words.count - 1; i > 0; --i) {
    int r = arc4random_uniform(i);
    [words exchangeObjectAtIndex:i withObjectAtIndex:r];
}

Now that we have a randomly shuffled array of words, we just take the first 4 elements and assign them to the buttons. It would look something like:

for (int j = 0; j < buttons.count; j++) {
    UIButton * button = [buttons objectAtIndex:j];
    button.titleLabel.text = [words objectAtIndex:j];
}

Finally we assign a word to the label, randomly choosing an index between the one we used for the buttons:

yourLabel.text = [words objectAtIndex:arc4random_uniform(buttons.count)];

This solution works with an arbitrary number of buttons, it's guaranteed to be efficient due to the shuffling algorithm (which is definitely better than checking for already generated indices) and the random generation is not biased thanks to the use of arc4random_uniform

Upvotes: 3

Jack Humphries
Jack Humphries

Reputation: 13267

Move the contents of the PLIST file into an array.

NSArray *words = [[NSArray alloc] initWithContentsOfFile:filePath];

Randomly find a number.

int randInt = arc4random() % 10;

Change 10 to the total number of words in the PLIST.

You can now select the random word out of the array.

NSString *random = [words objectAtIndex:randInt];

You have one random word. Find another random number (check to make sure it is not the same as the previous one) and then choose the next word out of the words array.

Upvotes: 2

Related Questions