Erreur lors de la création d'un nsarray à partir d'un plist?
-
05-07-2019 - |
Question
J'essaie de créer un NSArray à partir d'un fichier .plist, mais le message d'erreur suivant persiste:
" 'NSUnknownKeyException', reason: '[<NSCFString 0x5bbca60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Value1.'
"
Dans le fichier .plist, j'ai une clé appelée " Item 1 " et une valeur de chaîne appelée " Value1. " Puis dans le code, un NSArray est créé à partir de ce fichier:
-(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];
}
}
La solution
Les tableaux n'ont pas de clés (ils n'en ont pas besoin car leurs éléments sont adressés par leurs index), seuls les dictionnaires sont constitués de paires clé-valeur. Essayez:
for (id value in originalArray) {
NSLog(@"bundle: value=%@", value);
}
Autres conseils
Dans votre for
boucle, vous utilisez originalArray
comme un dictionnaire. Si la racine de votre plist est un dictionnaire, vous devez utiliser NSDictionary
et non NSArray
pour le lire.
Vous pouvez utiliser NSMutableArray immédiatement au lieu de NSArray et convertir en NSMutableArray. Assurez-vous également que votre pList est de type Array. Votre code aurait l'air:
-(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];
}
}