views:

490

answers:

2

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];
}
+1  A: 

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

Daniel
Ah. So that's what an array is. Thanks so much!
Evelyn
I'm still having trouble. Are you saying I need to create an array of dictionaries?
Evelyn
No, have the key be an array of numbers, instead of a number, an array is a list of Objects...so you can put as m any numbers in there as ud like...You want to make it a mutable array so you can add and remove from it.
Daniel
I meant the value not the key my bad, have the value be an array of numbers
Daniel
Oh okay! I think I got it. Thanks.
Evelyn
+1  A: 

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.

Corey Floyd
That helps too. :)
Evelyn