ios - NSUserdefaults 在 iOS 应用程序中无法正常工作

标签 ios objective-c nsuserdefaults

我有一个只显示一次设置页面的应用程序!这是它第一次从应用商店下载的时候。在那之后,它只进入主页。

但是当您双击 iPhone 按钮并删除应用程序时滑动应用程序,然后它会返回到设置页面。

这是我的应用程序中的一些代码

didfinishwithOptions

if (![[NSUserDefaults standardUserDefaults] boolForKey:@"SettingsShown"])
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"SettingsShown"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"ShowBackButton"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    self.window.rootViewController = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"SettingsViewController"];

}



if ([[NSUserDefaults standardUserDefaults] boolForKey:@"SettingsShown"] == NO)
{
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"SettingsShown"];
}

然后我把

- (void)applicationWillTerminate:(UIApplication *)application
{
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"SettingsShown"];
    NSLog(@"Application is terminated");
}

这应该在您双击 iPhone 按钮时滑动应用程序时运行。但它没有将用户默认值设置为 0,因为它正在从 didfinishwithoptions 再次运行设置页面。谁能建议?

最佳答案

NSUserDefaults 中的任何值都不一定立即写入。例如,如果您的应用程序以某种异常方式终止,则无法保证会写入数据。

您可以强制系统写入 NSUserDefaults,使用同步:

 [[NSUserDefaults standardUserDefaults] synchronize]

来自documentation :

Writes any modifications to the persistent domains to disk and updates all unmodified persistent domains to what is on disk. Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

这样做会有轻微的性能损失。

关于ios - NSUserdefaults 在 iOS 应用程序中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22940105/

相关文章:

ios - Swift - 从容器中的 TableView Controller 展开

ios - 栏按钮项目从导航 Controller 中消失

ios - VoiceOver 不读取 UITextField subview

iphone - 在我的应用程序中显示 FaceBook 个人资料

iOS - 调用 viewWillDisappear 时 NSUserDefaults 未保存

ios - 清除特定 NSUserDefaults 对象数据的数据

ios - TableView 部分标题中的视差效果会引发 UIView-nil 错误?

android - 如何使用 react-native 在 textInput 字段中自动获取 '/'(斜线)

objective-c - Cocos2d旋转关于触摸移动的问题

使用 KVO 和延迟选择器观察 NSUserDefaults 时的 iOS exc_bad_access