我的cocos2d游戏高分被写成了一个plist。每次进入plist时,只写入一行数据,每次写入plist时都会覆盖以前的数据?
继承我写给我的plist的代码:
-(void)writeToPlistHighScore {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,@"HighScore.plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] init];
[plistDict setObject:[NSNumber numberWithInteger:scoreNumber] forKey:@"Level2_HighScore"];
[plistDict writeToFile:filePath atomically: YES];
NSLog(@"HighScore wrote: %i", HighScore);
}
答案 0 :(得分:4)
那是因为你每次都在创建一个新的空NSDictionary。然后你添加一个分数并保存该字典。
您需要使用现有的plist初始化字典,以便字典加载现有的高分:
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile: writeToFile:filePath];
// if dictionary is nil the highscore file doesn't exist yet
if (plistDict == nil)
plistDict = [[NSMutableDictionary alloc] init];
另外,不要忘记在完成后发布字典!现在你正在泄露记忆。
[plistDict release];