我正在尝试从.plist文件创建一个NSArray,但我一直收到此错误:
“'NSUnknownKeyException', reason: '[<NSCFString 0x5bbca60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Value1.'
”
在.plist文件中,我有一个名为“Item 1”的键和一个名为“Value1”的字符串值。 然后在代码中我从该文件创建了一个NSArray:
-(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];
}
}
答案 0 :(得分:2)
数组没有键(它们不需要任何键,因为它们的元素由索引处理),只有字典由键值对组成。尝试:
for (id value in originalArray) {
NSLog(@"bundle: value=%@", value);
}
答案 1 :(得分:0)
在for
循环中,您使用的是originalArray
,就像字典一样。如果您的plist的根是字典,则应使用NSDictionary
,而不是NSArray
来阅读它。
答案 2 :(得分:0)
您可以立即使用NSMutableArray而不是NSArray并转换为NSMutableArray,同时确保您的pList是数组类型。你的代码看起来会是:
-(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];
}
}