¿Error al crear un nsarray desde plist?
-
05-07-2019 - |
Pregunta
Estoy intentando crear un NSArray a partir de un archivo .plist, pero sigo recibiendo este error:
" 'NSUnknownKeyException', reason: '[<NSCFString 0x5bbca60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Value1.'
"
En el archivo .plist, tengo una clave llamada " Elemento 1 " y un valor de cadena llamado " Value1. " Luego, en el código, se creó un NSArray a partir de ese archivo:
-(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];
}
}
Solución
Las matrices no tienen claves (no las necesitan porque sus elementos están direccionados por sus índices), solo los diccionarios consisten en pares clave-valor. Prueba:
for (id value in originalArray) {
NSLog(@"bundle: value=%@", value);
}
Otros consejos
En tu bucle for
, estás usando originalArray
como un diccionario. Si la raíz de su plist es un diccionario, debe usar NSDictionary
, no NSArray
para leerlo.
Puede usar NSMutableArray inmediatamente en lugar de NSArray y convertir a NSMutableArray, así también asegúrese de que su pList sea del tipo Array. Su código se vería:
-(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];
}
}