Atualizando e salvando dados em plist
Eu estou fazendo um jogo para iOS e preciso salvar o nível mais alto que o jogador alcançou. Posso alterar com êxito um elemento de dados em um plist, mas por algum motivo, esses dados continuam revertendo para seu valor original toda vez que o jogo é reiniciado. Aqui está o fluxo básico do meu código:
No init do jogo, obtenha o nível mais alto que o jogador atingiu (o valor original é 1)
pData = [[PlayerData alloc] init];
currentLevel = [[pData.data valueForKey:@"Highest Level"] intValue];
[self startNewLevel:currentLevel];
'data' é um NSMutableDictionary que é inicializado assim em PlayerData:
self.data = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"playerdata" ofType:@"plist"]];
mais tarde, se o jogador vencer o nível mais alto, eu incrementarei o valor do "nível mais alto" e gravarei no arquivo chamando essa função em PlayerData:
-(void) newHighestLevel:(NSString*)path :(int)level{
[self.data setValue:[NSNumber numberWithInt:level] forKey:path];
[self.data writeToFile:@"playerdata.plist" atomically:YES]
Eu sei que tudo isso está funcionando porque eu tenho um menu de nível que o jogador pode acessar enquanto joga o jogo. Cada vez que o jogador pressiona o botão do menu de nível, uma subclasse de um UITableView é criada, exibindo o nível 1 até o nível mais alto atingido. A inicialização é assim:
levelMenu = [[LevelMenu alloc] init:[[pData.data valueForKey:@"Highest Level"] intValue]];
O menu de nível exibe o número correto de níveis durante o jogo (por exemplo, se o jogador não tiver batido nenhum nível e for para o menu de nível, ele exibirá apenas "nível 1"; mas se o jogador vencer o nível 1 e for para o nível menu de nível, exibe "nível 1" e "nível 2"). No entanto, sempre que o aplicativo for encerrado ou o usuário sair do menu principal do jogo, o valor para 'nível mais alto' será revertido para 1 e este código:
currentLevel = [[pData.data valueForKey:@"Highest Level"] intValue];
sempre define currentLevel para 1 quando o jogador inicia, não importa quantos níveis o usuário bata enquanto joga.
Por que o valor está mudando de volta? Estou faltando alguma coisa que tornaria minhas edições plísticas permanentes?
EDITAR:
aqui está o meu novo método '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];
}
escrever fica definido como SIM. Se eu alterar 'docfilePath' para @ "playerdata.plist", ele será configurado como NO. Nada parece mudar com o jogo em ambos os casos.
SOLUÇÃO:
-(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];
}
e no 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;
}