0

我的 iphone 应用程序将键值对写入 plist 文件中的字典。我基本上是在用户玩游戏时保存用户的分数。这一切都很好,但每次我运行应用程序并获得新分数时,新值都会保存在旧值之上。每次用户访问应用程序而不是重写文件时,如何将信息添加到 plist?我想保留所有分数,而不仅仅是最近的分数。

代码:

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

2 回答 2

1

您正在将对象设置为关键分数的数字

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

而不是这个你想要做的是有一个数组或类似的东西

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

这应该可以满足您的要求

于 2009-07-29T16:59:11.750 回答
1

您想首先加载旧值,如 Daniel 所说,在 NSArray 或 NSDictionary 中。

您将新值添加到集合中。(也许也做一些排序或其他事情)

然后将新集合写回磁盘。

于 2009-07-29T17:04:56.853 回答