UserDefault.standard首选项仅正确保存了大约80%的时间

时间:2019-06-27 16:15:29

标签: swift nsuserdefaults userdefaults

这是我遇到的一个奇怪的问题。我正在设置和读取2个不同的布尔用户首选项。我根据用户正在执行的操作来更新用户首选项。然后,当用户再次打开应用程序时,我会阅读它们。当用户杀死该应用程序时,我总是看到正确调用了applicationWillTerminate,并且使用正确的值调用了两个设置器。再次打开应用程序时,这两个值是正确的(它们分别是最后设置为applicationWillTerminate)。但是,大约有20%的时间,它们是不正确的。我将一遍又一遍地做确切的场景,我将看到调用applicationWillTerminate并将2个变量设置为正确的值。但是,当我再次打开应用程序时,大约20%的时间它们不是更新值。我没有找到关于为何有时将值永久保存而有时却不永久保存的模式。

我已经对此进行了一段时间的研究,但找不到其他人遇到这个间歇性问题。我尝试添加syncnize(),即使它已被弃用,也没有任何区别。我知道我的二传手没有其他时间被叫过。

有什么想法吗?

//this method is called from didFinishLaunching and only that one time
private func checkForPriorCrash() {
    let appClosedProperly = UserDefaults.standard.bool(forKey: UserInterface.Keys.appClosedProperly)
    let lastStateWasActive = UserDefaults.standard.bool(forKey: UserInterface.Keys.lastStateWasActive)

    if !appClosedProperly && lastStateWasActive {
        print("**A CRASH HAPPENED LAST TIME")
    }
    UserDefaults.standard.removeObject(forKey: UserInterface.Keys.appClosedProperly) //reset
    UserDefaults.standard.removeObject(forKey: UserInterface.Keys.lastStateWasActive) //reset
}

private func setAppClosedProperly(_ value: Bool) {
    print("set did app closed properly")
    print(value)
    UserDefaults.standard.set(value, forKey: UserInterface.Keys.appClosedProperly)
}

private func setLastStateWasActive(_ value: Bool) {
    print("set last state was active")
    print(value)
    UserDefaults.standard.set(value, forKey: UserInterface.Keys.lastStateWasActive)
}

func applicationDidEnterBackground(_ application: UIApplication) {
    print("in applicationDidEnterBackground")
    setLastStateWasActive(false)
}

func applicationDidBecomeActive(_ application: UIApplication) {
    print("in applicationDidBecomeActive")
    setLastStateWasActive(true)
}

func applicationWillTerminate(_ application: UIApplication) {
    print("in applicationWillTerminate")
    setLastStateWasActive(false)
    setAppClosedProperly(true)
}

0 个答案:

没有答案