【问题标题】:Unable to save Integer using NSUserDefaults while exiting the app退出应用程序时无法使用 NSUserDefaults 保存整数
【发布时间】:2015-10-12 19:34:31
【问题描述】:

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

【问题讨论】:

  • 您是否在applicationWillTerminate: 中设置了断点以确保整数被存储?
  • 不工作是什么意思?它总是显示相同的值吗?
  • applicationWillTerminate 在应用程序将从内存中清除时被调用。换句话说,如果你把你的应用程序放到后台,然后再回到前台,这个方法就不会被调用。考虑使用applicationDidEnterBackgroundapplicationWillResignActive 来存储您的分数。要确认这一点,只需在applicationWillTerminate 的第一行设置断点,模拟背景/前景,您会看到您的应用不会暂停(断点命中)。
  • “在 Xcode 中”?您确定它是“在 Xcode 中”而不是在您的 iOS 应用中吗?
  • 感谢大家的cmets。如问题所述,我是初学者,所以我的方法不太专业。当我说它不起作用时,我的意思是当我重新打开我的应用程序时,该值被重置,是的,它在我的 iOS 应用程序中。我也不知道“设置断点”是什么,所以我没有这样做。再次感谢您的所有 cmets!

标签: ios objective-c int nsuserdefaults


【解决方案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 很有帮助。

【讨论】:

  • 谢谢!高分怎么加载?
  • 我试过了,但我收到以下警告,但它不起作用:'Incompatible pointer to integer conversion initializing 'int' with an expression of type 'id __nullable'
  • @CelceCode 确保你不是在说 int* 而不是 int。在某处,您正试图将指针转换为原始数据类型。
【解决方案2】:

使用 NSInteger 代替 int

NSInteger highScore=0;

存储它

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

然后把它找回来

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

【讨论】:

  • 这已被证明是最好的方法,因为我没有收到任何错误,但它也不起作用
【解决方案3】:

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

【讨论】:

  • 我就是这样做的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
相关资源
最近更新 更多