I am making an iOS game and must maintain the highest level the player has reached. I can successfully change the data item in plist, but for some reason, this data returns to its original value every time the game restarts. Here is the main stream of my code:
In the game init, get the maximum level that the player has reached (the initial value is 1)
pData = [[PlayerData alloc] init];
currentLevel = [[pData.data valueForKey:@"Highest Level"] intValue];
[self startNewLevel:currentLevel]
'data' is an NSMutableDictionary that is initialized this way in PlayerData:
self.data = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"playerdata" ofType:@"plist"]];
later, if the player hits the highest level, I increase the value of the "highest level" and write to the file, calling this function in PlayerData:
-(void) newHighestLevel:(NSString*)path :(int)level{
[self.data setValue:[NSNumber numberWithInt:level] forKey:path];
[self.data writeToFile:@"playerdata.plist" atomically:YES]
, , , , . , , UITableView, 1 . :
levelMenu = [[LevelMenu alloc] init:[[pData.data valueForKey:@"Highest Level"] intValue]];
(, , " 1", 1 , " 1" " 2" ). , , " " 1 :
currentLevel = [[pData.data valueForKey:@"Highest Level"] intValue];
currentLevel 1, , , .
? -, plist ?
EDIT:
newHighestLevel:
-(void) newHighestLevel:(NSString*)path :(int)level{
[self.data setValue:[NSNumber numberWithInt:level] forKey:path];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *docfilePath = [basePath stringByAppendingPathComponent:@"playerdata.plist"];
[self.data writeToFile:docfilePath atomically:YES];
self.data = [NSMutableDictionary dictionaryWithContentsOfFile:docfilePath];
BOOL write = [self.data writeToFile:docfilePath atomically:YES];
}
write YES. "docfilePath" @ "playerdata.plist", "". , .
:
-(void) newHighestLevel:(NSString*)path :(int)level{
[self.data setValue:[NSNumber numberWithInt:level] forKey:path];
NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *docfilePath = [basePath stringByAppendingPathComponent:@"playerdata.plist"];
[self.data writeToFile:docfilePath atomically:YES];
}
init
-(id) init{
NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *docfilePath = [basePath stringByAppendingPathComponent:@"playerdata.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:docfilePath]){
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"playerdata" ofType:@"plist"];
[fileManager copyItemAtPath:sourcePath toPath:docfilePath error:nil];
}
self.data = [NSMutableDictionary dictionaryWithContentsOfFile:docfilePath];
return self;
}