从plist中选择一个随机字符串并将其显示在文本字段中

时间:2012-12-09 01:20:15

标签: ios nsstring nsarray plist arc4random

嘿,我对iPhone编程非常陌生,我一直在网站和谷歌搜索我的问题的解决方案。基本上我正在尝试创建一个应用程序,从我的plist中选择一个随机字符串并将其显示在文本字段中。我已经尝试了无数种方法,但这种方式似乎效果最好,但是当我按下一个按钮并在arc4random线上给出错误“EXC_ARITHMETIC”时它仍然会崩溃。除了这个错误,当我按下按钮时,NSLog(@“items:& @”,items)在日志中显示项目:(null)。任何帮助或建议都非常感谢。 附: items是我已经在.h文件中设置的NSMutableArray

-(IBAction)buttonPress {
    NSString* path = [[NSBundle mainBundle] pathForResource:@"ItemList" ofType:@"plist"];
    items = [[NSMutableArray alloc]initWithContentsOfFile:path];
    NSLog(@"items: %@", items);
    NSInteger randomIndex = arc4random() % [items count];
    NSString* randomString = [items objectAtIndex:randomIndex];
    textField.text = randomString;
}

这是plist代码

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Array</key>
<array>
    <string>AAA</string>
    <string>BBB</string>
    <string>CCC</string>
    <string>DDD</string>
    <string>EEE</string>
    <string>FFF</string>
    <string>GGG</string>
    <string>HHH</string>
    <string>III</string>
    <string>JJJ</string>
</array>

再次感谢你们的帮助!

3 个答案:

答案 0 :(得分:0)

@Bryman我已经执行了你的代码,它对我来说很好。请重新创建plist文件。正如你所说它包含数组所以我已经通过将数组添加到plist文件来测试你的代码。

答案 1 :(得分:0)

你的问题是你的plist不是数组,它是一本字典。因此,您需要更改plist,或者需要将其作为字典阅读。

答案 2 :(得分:0)

很可能你根本无法读取plist,只检查你的plist结构,

 NSString *StringsFromPList = [[NSBundle mainBundle] bundlePath];
 NSString *itemPositionPlistLocation = [StringsFromPList stringByAppendingPathComponent:@"Words.plist"];
 _myDictionary= [[NSDictionary alloc] initWithContentsOfFile:itemPositionPlistLocation];
NSArray * items = [_myDictionary objectForKey:@"Root"];

你的plist应匹配此结构并从ROOT键读取而不是数组 希望能帮助到你 :) 别担心,我花了很长时间才发现为什么我无法阅读我的&gt;&lt;

<plist version="1.0">
<dict>
<key>Root</key>
    <array>
        <string>Happy</string>
        <string>Rain</string>
    </array>