我的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];
}
有帮助吗?

解决方案

您正在将对象设置为键得分

的数字
    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"]

这应该按照你的要求进行

其他提示

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

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

然后将新集合写回磁盘。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top