总结一下 iOS 上用 NSUserDefaults 存储配置无法加载的问题

2016-05-12 13:03:43 +08:00
 iAugus

Apple 从 Xcode7.3 的时候对 NSUserDefaults 做了修改 (SDK)

/*
 -synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release.
 
 -synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized...
 - ...before reading in order to fetch updated values: remove the synchronize call
 - ...after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify
 - ...before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
 - ...for any other reason: remove the synchronize call
 */
 
public func synchronize() -> Bool

然而出了 Bug ,配置莫名其妙的无法加载,于是 Apple 在 iOS9.3.1 的时候在系统层面暂时修复了这个 bug ,注意这时候 Xcode 最新版本还是 7.3 ,编译的 App 在使用过程中确实没有问题。

最近有网友说 iOS9.3.1 的配置丢失,当时我觉得奇怪,因为我一次都没有遇到过。但是在我升级到 Xcode7.3.1 后问题出来了,配置偶尔也无法加载。 这次 Apple 应该是从 SDK 层面修复了这个 bug ,你要做的就是像文档里说的那样不要再使用 synchronize() 了( synchronize is deprecated )

e.g: 比如我要存一个 Bool 值 (Swift)

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "yourKey")

这样就行了,不需要手动同步的

NSUserDefaults.standardUserDefaults().synchronize()	// Delete this line

在 iOS9.3.1 上测试是没有问题的,如果你有低版本的设备可以测试一下


以上是在这几个版本的 iOS 和 Xcode 的使用过程中的简单总结,可能不准确,欢迎指正。

4521 次点击
所在节点    iOS
4 条回复
xjbeta
2016-05-12 13:22:31 +08:00
前段时间也看到一篇文章(还是 stackoverflow)说 NSUserDefaults 已经没有必要使用 synchronize 进行手动同步了
iAugus
2016-05-12 13:30:17 +08:00
测试了 iOS 9.2 没有问题
iAugus
2016-05-12 13:31:09 +08:00
@xjbeta Xcode7.3 的时候就没有必要用了,但是当时有 bug
so898
2016-05-12 20:03:32 +08:00
前几天深受这个问题干扰,看了一圈还以为是模拟器的问题(真机无法重现),现在更新了 XCode 算是彻底好了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/278149

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX