Erro ao criar um NSArray de plist?
-
05-07-2019 - |
Pergunta
Eu estou tentando criar um NSArray de um arquivo .plist, mas eu continuo recebendo este erro:
"'NSUnknownKeyException', reason: '[<NSCFString 0x5bbca60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Value1.'
"
No arquivo .plist, tenho uma chave chamada "Item 1" e um valor de string chamado "Value1." Em seguida, no código eu tenho um NSArray sendo criado a partir desse arquivo:
-(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];
}
}
Solução
Arrays não têm chaves (eles não precisam de qualquer porque seus elementos são abordados por seus índices), apenas dicionários consistem de pares chave-valor. Tente:
for (id value in originalArray) {
NSLog(@"bundle: value=%@", value);
}
Outras dicas
Em seu loop for
, você está usando originalArray
como um dicionário. Se a raiz do seu plist é um dicionário, você deve usar NSDictionary
, não NSArray
para lê-lo.
Você pode usar NSMutableArray imediatamente em vez de NSArray e converter para NSMutableArray assim ter certeza que seu plist é tipo Array. Seu código ficaria:
-(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];
}
}