简体   繁体   English

如何从嵌套在plist文件的字典中的数组访问随机值?

[英]How do I access random values from an array nested in a dictionary from plist file?

Basically I need to get a random letter and the points associated with that letter from a plist. 基本上,我需要从plist中获取随机字母和与该字母相关的点。 I'm honestly not sure I have my plist set up in the best possible way to do this, I've never worked with plist before: 老实说,我不确定我是否已以最佳方式设置了plist,但我之前从未使用过plist: 在此处输入图片说明

As soon as I get this working I'm going to be adding CZ into the plist with each letters associated points. 一旦开始工作,我将在每个字母关联点的plist中添加CZ。 I'm just created a basic word tile game to try and learn sprite kit. 我刚刚创建了一个基本的单词拼贴游戏,尝试学习Sprite Kit。

So far I've been able to access the plist file but have not had any luck getting a random Letter and it's Points.I'm getting all kinds of errors with everything I try. 到目前为止,我已经能够访问plist文件,但是没有得到任何随机的Letter和Points的运气。我尝试的所有方法都遇到各种错误。

Here's my code so far to access the plist:
        NSString* fileName = @"letters.plist";
        NSString* filepath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];

        NSDictionary* lettersPlist = [NSDictionary dictionaryWithContentsOfFile:filepath];
        NSDictionary* letters = lettersPlist[@"letters"];

So how do I get a random letter and it's points from this plist? 那么,如何从该plist中获得随机字母及其要点呢? And is there a better way to do this? 还有更好的方法吗?

Just get a random number between 0 and the number of items in your letters array, and take that info out. 只需获取介于0和letters数组中项目数之间的随机数,然后取出该信息即可。 For example, continuing your code: 例如,继续执行代码:

u_int32_t bound = (u_int32_t)[letters count];
NSDictionary* randomLetterInfo = letters[arc4random_uniform(bound)];
NSString* randomLetter = randomLetterInfo[@"Letter"];
NSString* points = randomLetterInfo[@"Points"]; // points are a string in your plist

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM