我有一个int
名为的值score
,我想将其保存到手机的内存中,这样即使游戏关闭并重新打开,这也是永远不会删除的高分,
有人可以建议一种方法来实现吗?
使用NSUserDefaults
.
保存:
int score = 12345;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:score] forKey:@"HIGHSCORE"];
装载:
int score = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HIGHSCORE"] integerValue];
您应该阅读 Apple 文档NSUserDefaults
参见NSUserDefaults和Preferences and Settings 编程指南
[[NSUserDefaults standardUserDefaults] setInteger: score forKey: @"Score"]
在我看来,保存最佳分数的简单方法是将分数保存为字符串值,并在需要时将其召回。
//this example assume that high score is in text
NSString *SaveHighScore = HighScore.text;
NSUserDefaults *defaultsHighScore = [NSUserDefaults standardUserDefaults];
[defaultsHighScore setObject:SaveHighScore forKey:@"savedHighScore"];
[defaultsHighScore synchronize];
并回忆
NSUserDefaults *defaultsHighScore = [NSUserDefaults standardUserDefaults];
NSString *loadHighScore = [defaultsHighScore objectForKey:@"savedHighScore"];
[HighScore setText :loadHighScore];