objective-c - 从从 plist 导入的 nsdictionary 生成随机句子

标签 objective-c ios xcode plist nsdictionary

我将这个 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"];

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

感谢您的帮助!

最佳答案

首先,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]

然后使用索引选择一个随 secret 钥:

int randomIndex = arc4random() % (keys.count);
NSString* key = [plisttext2 objectForKey:[keys objectAtIndex:randomIndex]];

使用随机选择的键,您可以访问书中的句子,并使用相同的方法随机选择它们。选择后,将它们全部加在一起,就得到了结果。

这意味着您可以从不同的书中生成随机句子,同时仍然能够显示句子编号 + 书名(因为您保留了引用它们的索引)。

关于objective-c - 从从 plist 导入的 nsdictionary 生成随机句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13050339/

相关文章:

objective-c - 基于文档的应用程序的核心数据版本控制

objective-c - 关闭ModalViewController后未传回值

iphone - 有可能知道 CLLocation 点是否在 MKCoordinateRegion 中?

ios - 在运行时在 objective-c 中获取类对象的大小

ios - 如何创建一组由 OR 而不是 AND 连接的 MPMediaPropertyPredicate

ios - 在 Swift 中编写 Kvo 上下文

ios - PhaseScriptExecution 因构建 IOS 的 jenkins 中的非零退出代码错误而失败

iphone - 如何更改 UITextField clearButton 的颜色?

Xcode Clang 总线错误 10

ios - 当我使用数组时 Xcode 8 永远索引