显示plist中的随机单词 [英] displaying a random word from a plist

查看:102
本文介绍了显示plist中的随机单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在其中列出了一些单词,现在我尝试从该plist中显示一个随机单词

I made a p list with some words in it now I try to display a random word out of that plist

这是我的代码

NSArray *randomAddons = [NSArray arrayWithContentsOfFile: @"wordsENG.plist"];
int randomIndex = arc4random() % [randomAddons count];
mainTextController.text = [username2 stringByAppendingString:[randomAddons objectAtIndex:randomIndex]];

当我更改%[randomAddons count]时崩溃到%3;它崩溃但我不知道如何正确编码这可以有人帮助我吗?

This crashes and when I change % [randomAddons count]; to % 3; it crashes to but I don't know how to correctly code this Can someone help me out?

谢谢

编辑:

我编辑的plist文件存在问题,根据提供的链接jackjr300,请查看下面的注释。我仍然留下从一开始就得到的崩溃。崩溃说:

There was a problem with the plist file I edited that according to the link jackjr300 provided, look at the comment below. Still I am left with the crashes that I got from beginning. the crash says:

Array: (
        (
        SAMSAM,
        SELSEL,
        DONDON
    )
)
2012-07-10 03:41:11.048 spinningyarn[1590:1bb03] -[__NSCFArray length]: unrecognized selector sent to instance 0xcfcfdd0
2012-07-10 03:41:11.048 spinningyarn[1590:1bb03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray length]: unrecognized selector sent to instance 0xcfcfdd0'
*** First throw call stack:
(0x1b04022 0x1ee0cd6 0x1b05cbd 0x1a6aed0 0x1a6acb2 0x1468bd9 0x115dc3 0x3de995 0x979ed9 0x981725 0x8ea4ab 0x9837c6 0x8c9885 0x2166330 0x2168509 0x1a3b803 0x1a3ad84 0x1a3ac9b 0x26287d8 0x262888a 0xb3d626 0x29e2 0x2955 0x1)
terminate called throwing an exception(lldb) 

SAMSAM,SELSEL,DONDON是我的P列表文件中的3个单词

SAMSAM, SELSEL, DONDON being the 3 words in my P list file

推荐答案

问题是plist文件不是数组,它是一个dictio nary :)

代码应该是(假设是,有为key存储的单词数组(keyForArray):

(正确的实现取决于Dictionary中的entires - 如何添加行plist文件)

Problem is plist file is not an array, its a dictionary :)
code should be (Assumption is, there is array with words stored for key (keyForArray):
(correct implementation depends on entires in Dictionary - how rows are added to plist file)

NSDictionary *randomEntriesDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wordsENG" ofType:@"plist"]];

NSUInteger dictionaryCount = [randomEntriesDictionary count];
if(nil != dictionaryCount)
{
   NSArray *randomWords = [randomEntriesDictionary objectForKey:keyForArray];
   NSUInteger randomIndex = arc4Random % dictionaryCount;
   NSString *randomWord = [randomWords objectAtIndex:randomIndex];
}
else
{
  // check if file exists  and not empty?
  // is it in plist format ?
  ... do the needed.
}

这篇关于显示plist中的随机单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆