显示plist中的随机单词

时间:2012-07-10 00:21:08

标签: iphone objective-c xcode

我在其中创建了一个带有一些单词的列表,现在我尝试从该plist中显示一个随机单词

这是我的代码

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

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

感谢

修改

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

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个单词

3 个答案:

答案 0 :(得分:1)

问题是plist文件不是数组,它是一个字典:) 代码应该是(假设是,存在用于键存储的单词的数组(keyForArray):
(正确的实现取决于字典中的entires - 如何将行添加到plist文件中)

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

答案 1 :(得分:0)

您的文件似乎未正确包含在应用的主要捆绑包中。在项目导航器中,单击项目,然后选择应用程序的目标。选择“Build Phases”部分,然后查找“Copy Bundle Resources”构建阶段。如果您没有,可以使用“添加构建阶段”按钮创建一个。

一旦有了Copy Bundle Resource构建阶段,请确保您的plist文件在该部分中列为bundle资源。如果不是,您可以按+按钮添加它,或将文件从主项目导航器文件列表拖到捆绑资源列表中。

完成此操作后,您可以重建并将文件包含在捆绑包中。如果该文件在您的包中,您可以使用另一个答案中建议的[[NSBundle mainBundle] pathForResource:@"wordsENG" ofType@"plist"]

答案 2 :(得分:-1)

如数组中所示的控制台数组所示。所以试试这个希望它对你有帮助......

NSArray *randomAddons = [NSArray arrayWithContentsOfFile: @"wordsENG.plist"];

NSArray *randomArray = [[NSArray alloc] initWithObjects:[ randomAddons objectAtIndex:0], nil];

int randomIndex = arc4random() % [randomArray count];
mainTextController.text = [username2 stringByAppendingString:[randomArray objectAtIndex:randomIndex]];
相关问题