我是一个想要在我的应用程序中存储int值(高分)的初学者,所以当用户从多任务关闭应用程序并再次打开它时,它将获取数据并显示它。
我尝试使用NSUserDefaults,但是当我再次打开应用程序时它不会出现。这是我使用的代码:
// Used this to load the high score from the memory
highscoreInt = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"highscore"];
// And this to store it, later in the code
- (void)applicationWillTerminate:(UIApplication *)application
{
[[NSUserDefaults standardUserDefaults] setInteger:highscoreInt forKey:@"highscore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
答案 0 :(得分:1)
我会将整数包装在NSNumber
对象中,并将其放在applicationDidEnterBackground
中,如下所示:
// Use this method to release shared resources, save user data,
// invalidate timers, and store enough application state information to
// restore your application to its current state in case it is terminated later.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
highscoreInt = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"highscore"];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScoreInt] forKey:@"highscore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
当您需要加载分数时,请在您要加载分数的任何方法中执行以下操作:
int highScore = [[NSUserDefaults standardUserDefaults] objectForKey:@"highscore"];
在阅读NSUserDefaults
时,您会发现此link有用。
答案 1 :(得分:1)
使用 NSInteger 而不是int
NSInteger highScore=0;
存储它
[[NSUserDefaults standardUserDefaults] setInteger:highScore forKey:@"HighScore"];
并将其取回
NSInteger highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"];
答案 2 :(得分:0)
我强烈建议每当更改时保存高分。