Reputation: 121
I created this plist as dictionary to keep book names as keys:
<dict>
<key>Frankestein</key>
<dict>
<key>0</key>
<string>his name was frank</string>
<key>1</key>
<string>he was a monster</string>
</dict>
<key>dracula</key>
<dict>
<key>0</key>
<string>his name was dracula</string>
<key>1</key>
<string>he was a vampire</string>
</dict>
</dict>
</plist>
then loaded the plist into dictionary:
NSDictionary *plisttext2 = [NSDictionary dictionaryWithContentsOfFile:@"text2.plist"];
How would i be able to generate and display random sentences from the dictionary, and show the sentence number and book name (keys) ?
Thanks for your help!!
Upvotes: 1
Views: 807
Reputation: 19030
For one, NSDictionary *plisttext2 = [NSDictionary dictionaryWithContentsOfFile:@"text2.plist"];
will not work. The ContentsOfFile
parameter expects a full path, not a relative path file name. In order to do this, use:
NSBundle* bundle = [NSBundle mainBundle];
NSString* plistPath = [bundle pathForResource:@"text2" ofType:@"plist"];
NSDictionary* plisttext2 = [NSDictionary dictionaryWithContentsOfFile:plistPath];
Now to generate and display random sentences, you would need to keep a track of all the keys:
NSArray* keys = [plisttext2 allKeys]
Then select a random key using the index:
int randomIndex = arc4random() % (keys.count);
NSString* key = [plisttext2 objectForKey:[keys objectAtIndex:randomIndex]];
Using the randomly selected key, you can then access the book's sentences, and use the same method to select them at random. After selection, add them all together, and you have your result.
This means you can generate random sentences from different books, whilst still being able to show the sentence number + book name (as you've kept ahold of their indices that refer to them).
Upvotes: 1
Reputation: 3629
You could iterate through the plist to determine max key values for each dictionary then do something similar to the code below to randomly select a sentence from each dictionary.
int min = 0;
int max = iterationResult;
int randNum = rand() % (max-min) + max; //create the random number.
NSLog(@"RANDOM NUMBER: %i", randNum);
Upvotes: 0