Domanda

Sto cercando di creare un NSArray da un file .plist, ma continuo a ricevere questo errore:

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

Nel file .plist, ho una chiave chiamata " Item 1 " e un valore stringa chiamato " Valore1. " Quindi nel codice ho creato un NSArray da quel file:

-(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];

}

    }
È stato utile?

Soluzione

Le matrici non hanno chiavi (non ne hanno bisogno perché i loro elementi sono indirizzati dai loro indici), solo i dizionari sono costituiti da coppie chiave-valore. Prova:

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

Altri suggerimenti

Nel tuo ciclo for, stai usando originalArray come un dizionario. Se la radice del tuo plist è un dizionario, dovresti usare NSDictionary, non NSArray per leggerlo.

È possibile utilizzare NSMutableArray immediatamente anziché NSArray e convertirlo in NSMutableArray, nonché accertarsi che la propria lista pista sia di tipo Array. Il tuo codice sarebbe:

-(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];
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top