Swift 3 不保存 UserDefaults [英] UserDefaults is not saved with Swift 3

查看:55
本文介绍了Swift 3 不保存 UserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 UserDefaults 来持久保存一个布尔值.这是我的代码:

I'm trying to use the UserDefaults to persistently save a boolean value. This is my code :

public static var isOffline = UserDefaults.standard.bool(forKey: "isOffline") {
        didSet {
            print("Saving isOffline flag which is now \(isOffline)")
            UserDefaults.standard.set(isOffline, forKey: "isOffline")
            UserDefaults.standard.synchronize()
        }
    }

为什么不起作用?这段代码有什么问题?

Why doesn't work? What is the problem in this code?

问题是,当我尝试从 UserDefaults 检索 "isOffline" 键时,我总是得到 false.

The problem is that when I try to retrieve "isOffline" key from UserDefaults I always get a false.

编辑 2:我在行的 .onChange 方法中设置了 isOffline (我使用 Eureka 作为框架来创建表单).该标志在应用程序的生命周期中保持正确的值,但是当我关闭它时,该值可能会以某种方式被删除.

EDIT 2: I set the isOffline in the .onChange method of the row (I'm using Eureka as framework to create forms). The flag keep the right value during the lifecycle of the app, but when I close it that value is probably removed in some way.

推荐答案

我遇到了同样的问题,问题出在didSet"块本身.我不知道为什么,但它不适用于 userDefaults - 它没有正确地保留它,并且在杀死应用程序后所有更改都消失了.

I had the same problem and the issue was in the "didSet" block itself. I don't know why, but it does not work with userDefaults - it does not persist it properly and after killing the application all changes were gone.

Synchronize() 没有帮助.我发现,此方法不再需要,将来会被弃用(这是 UserDefaults 类中的注释):

Synchronize() does not help. I found out, this method is no longer necessary and it will be deprecated in future (this is comment in UserDefaults class):

-synchronize 已弃用,并将在未来版本中使用 NS_DEPRECATED 宏进行标记.

-synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release.

通过反复试验,我发现它可以工作,如果我从主线程调用它:

By trial and error I found out, that it works, if I call it from main thread:

public static var isOffline = UserDefaults.standard.bool(forKey: "isOffline") {
        didSet {
            print("Saving isOffline flag which is now \(isOffline)")
            DispatchQueue.main.async {
                    UserDefaults.standard.set(isOffline, forKey: "isOffline")
                }

        }
    }

如果有人能解释一下,为什么它在主线程上工作而不是在其他线程上工作,我会很高兴听到.

If anyone can explain, why it works on main thread and no other, I would be glad to hear it.

这篇关于Swift 3 不保存 UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆