1

我正在尝试从 .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];

}

    }
4

3 回答 3

2

数组没有键(它们不需要任何键,因为它们的元素由它们的索引寻址),只有字典由键值对组成。尝试:

for (id value in originalArray) {
            NSLog(@"bundle: value=%@", value);
    }
于 2009-07-30T19:52:00.510 回答
0

在你的for循环中,你originalArray像字典一样使用。如果你的 plist 的根是字典,你应该使用NSDictionary,而不是NSArray阅读它。

于 2009-07-30T19:40:41.813 回答
0

您可以立即使用 NSMutableArray 而不是 NSArray 并转换为 NSMutableArray 并确保您的 pList 是 Array 类型。您的代码如下所示:

-(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];
}
}
于 2015-03-07T01:20:38.310 回答