V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
iAugus
V2EX  ›  iOS

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

  •  
  •   iAugus · 2016-05-12 13:03:43 +08:00 · 4510 次点击
    这是一个创建于 2906 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 的使用过程中的简单总结,可能不准确,欢迎指正。

    4 条回复    2016-05-12 20:03:32 +08:00
    xjbeta
        1
    xjbeta  
       2016-05-12 13:22:31 +08:00
    前段时间也看到一篇文章(还是 stackoverflow)说 NSUserDefaults 已经没有必要使用 synchronize 进行手动同步了
    iAugus
        2
    iAugus  
    OP
       2016-05-12 13:30:17 +08:00
    测试了 iOS 9.2 没有问题
    iAugus
        3
    iAugus  
    OP
       2016-05-12 13:31:09 +08:00
    @xjbeta Xcode7.3 的时候就没有必要用了,但是当时有 bug
    so898
        4
    so898  
       2016-05-12 20:03:32 +08:00
    前几天深受这个问题干扰,看了一圈还以为是模拟器的问题(真机无法重现),现在更新了 XCode 算是彻底好了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   981 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 19:55 · PVG 03:55 · LAX 12:55 · JFK 15:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.