Salvare ulteriori informazioni in una lista ogni volta che eseguo l'app? (i phone)
-
05-07-2019 - |
Domanda
La mia app per iPhone scrive coppie chiave-valore in un dizionario in un file plist. Fondamentalmente sto salvando il punteggio dell'utente quando giocano. Tutto questo va bene e dandy, ma ogni volta che eseguo l'app e ottengo nuovi punteggi, i nuovi valori vengono salvati rispetto ai vecchi valori. Come faccio ad aggiungere informazioni al plist ogni volta che l'utente accede all'app invece di riscrivere il file? Voglio mantenere tutti i punteggi, non solo il più recente.
codice:
-(void)recordValues:(id)sender {
//read "propertyList.plist" from application bundle
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path
stringByAppendingPathComponent:@"propertyList.plist"];
dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
//create an NSNumber object containing the
//float value userScore and add it as 'score' to the dictionary.
NSNumber *number=[NSNumber numberWithFloat:userScore];
[dictionary setObject:number forKey:@"score"];
//dump the contents of the dictionary to the console
for (id key in dictionary) {
NSLog(@"memory: key=%@, value=%@", key, [dictionary
objectForKey:key]);
}
//write xml representation of dictionary to a file
[dictionary writeToFile:@"/Users/rthomas/Sites/propertyList.plist" atomically:NO];
}
Soluzione
Stai impostando l'oggetto su un numero per il punteggio chiave
NSNumber *number=[NSNumber numberWithFloat:userScore];
[dictionary setObject:number forKey:@"score"];
Invece di ciò che vuoi fare è avere un array o qualcosa del genere, quindi
NSNumber *number=[NSNumber numberWithFloat:userScore];
NSMutableArray *array=[dictionary objectForKey:@"score"]
[array addObject:number]
[dictionary setObject:array forKey:@"score"]
questo dovrebbe fare quello che stai chiedendo
Altri suggerimenti
Prima vuoi caricare i vecchi valori, in un NSArray o NSDictionary come ha detto Daniel.
L'aggiunta del nuovo valore alla raccolta. (forse fai un po 'di ordinamento o qualcosa del genere)
Quindi riscrivi la nuova raccolta su disco.