简体   繁体   English

NSUserdefaults在iOS应用中无法正常工作

[英]NSUserdefaults are not working correctly in iOS app

I have an app which shows the settings page ONCE! 我有一个显示设置页面一次的应用程序! This is when it is first download from the app store. 这是第一次从应用商店下载。 After that then it goes to the main page only. 之后,它将仅进入主页。

but when you swipe the app when you double click the iPhone button and remove the app then it goes back to the settings page. 但是,当您双击iPhone按钮并删除该应用程序时,当您轻扫该应用程序时,它将返回到设置页面。

Here is some code from my app 这是我的应用程序中的一些代码

didfinishwithOptions 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"];
}

then I have put 然后我把

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

this should run when you swipe the application when you double click on the iPhone button. 当您双击iPhone按钮时,当您滑动应用程序时,它应该会运行。 but it isn't setting the user default to 0 because it is running the settings page again from didfinishwithoptions. 但未将用户默认设置设为0,因为它再次从didfinishwithoptions运行设置页面。 Can anyone advise ? 有人可以建议吗?

Any value put into NSUserDefaults is not necessarily written instantly. 放入NSUserDefaults任何值都不必立即写入。 If you app, for instance, terminates in some unusual way, there is no guarantee, the data will be written. 例如,如果您的应用程序以某种异常方式终止,则不能保证将写入数据。

You can force the system to write to the NSUserDefaults , using synchronize: 您可以使用同步来强制系统写入NSUserDefaults

 [[NSUserDefaults standardUserDefaults] synchronize]

From the 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. 因为此方法是定期自动调用的,所以仅当您无法等待自动同步时(例如,如果您的应用程序将要退出),或者您想要将用户默认值更新为磁盘上的默认值时,才使用此方法。您尚未进行任何更改。

There is a minor performance penalty doing so. 这样做会有轻微的性能损失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM