退出应用程序时无法使用 NSUserDefaults 保存整数

Unable to save Integer using NSUserDefaults while exiting the app

我是一个初学者,想在我的应用程序中存储一个 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];
}

我会将整数包装在一个 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"];

你会发现这个 link 在阅读 NSUserDefaults 时很有帮助。

我强烈建议在高分发生变化时保存它。

使用 NSInteger 而不是 int

NSInteger highScore=0;

存储它

[[NSUserDefaults standardUserDefaults] setInteger:highScore forKey:@"HighScore"];

并取回它

NSInteger highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"];