views:

294

answers:

2

I am trying to create an NSArray from a .plist file, but I keep getting this error:

"'NSUnknownKeyException', reason: '[<NSCFString 0x5bbca60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Value1.'"

In the .plist file, I have a key called "Item 1" and a string value called "Value1." Then in the code I have an NSArray being created from that file:

-(void)recordValues:(id)sender {

    // read "propertyList.plist" values
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"propertyList" ofType:@"plist"];
    originalArray = [[NSArray alloc] initWithContentsOfFile:plistPath];

   // dump the contents of the array to the log
    for (id key in originalArray) {
     NSLog(@"bundle: key=%@, value=%@", key, [originalArray valueForKey:key]);
    }

    //create an NSMutableArray containing the
    //user's score and the values from originalArray
    NSMutableArray *newArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithFloat:userScore], nil];
    [newArray addObjectsFromArray:array];

    //write xml representation of mutableArray back to propertyList
    [newArray writeToFile:plistPath atomically:NO];

}

    }
A: 

In your for loop, you're using originalArray like a dictionary. If the root of your plist is a dictionary, you should use NSDictionary, not NSArray to read it.

Alex
the root is an NSArray. How do I read it as an NSArray then? I need to add values, and I can't add values with an NSDictionary.
Evelyn
A: 

Arrays do not have keys (they don't need any because their elements are addressed by their indices), only dictionaries consist of key-value pairs. Try:

for (id value in originalArray) {
            NSLog(@"bundle: value=%@", value);
    }
Rüdiger Hanke
Yay! It worked.
Evelyn