1

我将此 plist 创建为字典,以将书名作为键:

<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>

然后将 plist 加载到字典中:

NSDictionary *plisttext2 = [NSDictionary dictionaryWithContentsOfFile:@"text2.plist"];

我如何能够从字典中生成和显示随机句子,并显示句子编号和书名(键)?

谢谢你的帮助!!

4

2 回答 2

1

一方面,NSDictionary *plisttext2 = [NSDictionary dictionaryWithContentsOfFile:@"text2.plist"];行不通。该ContentsOfFile参数需要一个完整路径,而不是相对路径文件名。为此,请使用:

NSBundle* bundle = [NSBundle mainBundle];
NSString* plistPath = [bundle pathForResource:@"text2" ofType:@"plist"];
NSDictionary* plisttext2 = [NSDictionary dictionaryWithContentsOfFile:plistPath];

现在要生成和显示随机句子,您需要跟踪所有键:

NSArray* keys = [plisttext2 allKeys]

然后使用索引选择一个随机键:

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).

于 2012-10-24T13:41:55.617 回答
0

您可以遍历 plist 以确定每个字典的最大键值,然后执行类似于以下代码的操作以从每个字典中随机选择一个句子。

int min = 0; 
int max = iterationResult;
int randNum = rand() % (max-min) + max; //create the random number.
NSLog(@"RANDOM NUMBER: %i", randNum); 
于 2012-10-24T13:37:28.647 回答