userdefaults 第一次后未保存

userdefaults not being saved after first time

我创建了一些简单的系统,如果 userdefaults 有密钥 "isWalkthroughPresented"。如果密钥是 false 则显示 walkthourghViewController。如果没有密钥,则从数据库中检查。

但是第一次后并没有设置密钥。但在一些发射后保存。应该是什么问题?

这是我在用户登录并看到第二个 ViewController:

后在 viewDidAppear 中使用的代码
let userDefaults = UserDefaults.standard

        if !userDefaults.bool(forKey: "isWalkthroughPresented") {

            presentWalkthrough()

            userDefaults.set(true, forKey: "isWalkthroughPresented")

        }else{
            checkIfCurrentUserHasOpenedTheAppBefore()//this just checks if user in db has the value
        }

设置用户默认值后,调用此命令强制将更改保存到数据库:

//...
userDefaults.set(true, forKey: "isWalkthroughPresented")
userDefaults.synchronize()

通常会定期调用 synchronize() 方法将缓存的用户设置保存到数据库中。设置 "isWalkthroughPresented" 和再次读取之间的间隔不足以自动调用 synchronize()

另请参阅 method documentation 中的这些详细信息:

Because this method [synchronize()] 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.