Question

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];

}

    }
Was it helpful?

Solution

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

OTHER TIPS

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.

You can use NSMutableArray immediately instead of NSArray and convert to NSMutableArray as well be sure that your pList is Array type. Your code would look:

-(void)recordValues:(id)sender {
// read "propertyList.plist" values
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"propertyList" ofType:@"plist"];
//create an NSMutableArray containing the
//user's score and the values from originalArray
NSMutableArray *array = [NSArray arrayWithContentsOfFile: path];
[newArray addObjectsFromArray:array];
//check-out the content
NSLog(@"The content of the array: %@", array);
//write xml representation of mutableArray back to propertyList
[array writeToFile:plistPath atomically:NO];
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top