Question

My iphone app writes key-value pairs to a dictionary in a plist file. I'm basically saving the user's score when they play the game. This is all fine and dandy, but each time I run the app and get new scores, the new values get saved over the old values. How do I add information to the plist each time the user accesses the app instead of rewriting the file? I want to keep all of the scores, not just the most recent one.

code:

-(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];
}
Was it helpful?

Solution

You are setting the object to a number for key score

    NSNumber *number=[NSNumber numberWithFloat:userScore];   
 [dictionary setObject:number forKey:@"score"];

Instead of this what you want to do is have an array or something of the sort so

NSNumber *number=[NSNumber numberWithFloat:userScore];  
    NSMutableArray *array=[dictionary objectForKey:@"score"]
     [array addObject:number]
    [dictionary setObject:array forKey:@"score"]

this should do what you are asking

OTHER TIPS

You want to load the old values first, in a NSArray or NSDictionary like Daniel said.

The you add the new value to the collection. (maybe do some sorting or something also)

Then you write the new collection back to disk.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top