我正在尝试从.plist文件创建NSArray,但我一直收到此错误:

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

在.plist文件中,我有一个名为<!>的键;项目1 <!>“;和一个名为<!>的字符串值; Value1。<!> quot; 然后在代码中我从该文件创建了一个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];

}

    }
有帮助吗?

解决方案

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

for (id value in originalArray) {
            NSLog(@"bundle: value=%@", value);
    }

其他提示

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

您可以立即使用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];
}
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top