سؤال

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!

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

@Bryman I've executed your code it is working fine for me. Please once recreate your plist file. As you are saying it contains array so I've tested your code by adding array to a plist file.

Most likely your simply not being able to read the plist, just check your plist structure,

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

your plist should match this structure and be reading from the ROOT key not array hope it helps :) dont worry it took me ages to find why i couldnt read mine ><

<plist version="1.0">
<dict>
<key>Root</key>
    <array>
        <string>Happy</string>
        <string>Rain</string>
    </array>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top