gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:42:14 35 4
gpt4 key购买 nike

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

关于ios - 退出应用程序时无法使用 NSUserDefaults 保存整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31571385/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com