OGeek|极客世界-中国程序员成长平台

标题: ios - Xcode 9 模拟器不保存 userdefaults [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:46
标题: ios - Xcode 9 模拟器不保存 userdefaults

也许这与 this 是同一个问题。但我尝试过的解决方案中,很少有不起作用的。

模拟器不会在 Xcode 版本 9.0 beta 6 (9M214v) 上保存用户默认值。 我也有 Xcode 8(连同 9)但删除了它。

我正在使用的代码:

UserDefaults.standard.setValue("1234567", forKey: "phone")
if let phone = UserDefaults.standard.value(forKey: "phone") as? String{
  //some code here
}

另外我试过:

UserDefaults.standard.set("1234567", forKey: "phone")
if let phone = UserDefaults.standard.object(forKey: "phone") as? String{
  //some code here
} 



Best Answer-推荐答案


对于synchronize 的作用以及用户默认值的编写方式存在很多误解。在猜测事情如何运作之前,请务必检查 current maintainer's commentary关于它。他对事情很清楚。他的analogy to git也有点用处,请参阅他关于 iOS 8 的注释变化。对于这样一项古老的技术,NSUserDefaults 的变化比你想象的要多得多。

总而言之,在生产应用中几乎不需要调用 synchronize。 (事实上​​ ,关于弃用和删除它的讨论反复出现。)正如文档所述:

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.

即使是这些案例也大多与 macOS 相关。

For applications running on iOS 9.3 and later / macOS Sierra and later, -synchronize is not needed (or recommended) even in this situation [synchronizing between processes], since Key-Value Observation of defaults works between processes now, so the reading process can just watch directly for the value to change. As a result of that, applications running on those operating systems should generally never call synchronize.

但是......

人们在模拟器中使用用户默认设置时遇到的常见问题是,他们会在写入发生之前终止应用程序(点击停止、重新启动应用程序、崩溃)。在生产中,这通常不是问题。如果你在写入用户默认值的时候崩溃了,很可能你处于一个定义不明确的状态,所以无论你写的是垃圾,还是写的好,或者什么都没写,都是一种折腾-你喜欢什么。但是在开发过程中,程序终止总是会发生,这通常会导致用户默认值不写出。

现在一个似乎经常可行的解决方案是在各处散布 synchronize。但在大多数情况下,这只会减慢您的代码速度。如果它有效,很好。但在我从事的大多数项目中,真正的解决方案只是在终止应用程序之前先喘口气。它不需要很多时间;只是不要在应用程序有机会写入您保存的内容之前终止该应用程序,然后重新启动以检查它是否已保存。

关于ios - Xcode 9 模拟器不保存 userdefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46526460/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4