Search code examples
iosnsstringnsarrayplistarc4random

Selecting a random string from a plist and displaying it in a text field


Hey I'm very new to iPhone programming and I have been searching for hours both on this site and on google for the solution to my problem. Basically I am trying to make an app which selects a random string out of my plist and displays it into a text field. I have tried countless ways, but this way seems to work the best, however it still crashes when I press a button and gives me the error "EXC_ARITHMETIC" on the arc4random line. As well as this error, the NSLog(@"items: &@", items) displays items: (null) in the log when i press the button. Any help or suggestions are GREATLY appreciated. P.S. items is an NSMutableArray I already set up in the .h file

-(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;
}

Here's the plist code

<?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>

Thanks guys again for all your help!


Solution

  • Your problem is that your plist is not an array, it is a dictionary. So either you need to change your plist,or you need to read it in as a dictionary instead.