NSUserDefaults同步方法

sha*_*jem 49 iphone cocoa-touch

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"xxxxxxxx" forKey:@"name"];

[defaults synchronize];
Run Code Online (Sandbox Code Playgroud)

我需要知道为什么我必须使用上面代码的最后一行[defaults synchronize]?使用它的目的是什么?这是必须的吗?

Dar*_*ust 98

目的[default synchronize];是使用户默认值立即写入磁盘.你不需要明确地调用它,iOS已经在适当的时候完成它.所以你可以删除该行.实际上,如果synchronize每次设置默认值时调用都会出现性能问题.

在iOS 7之前,当应用程序转换为后台时,用户默认值始终是同步的.从iOS 7开始,情况已经不再如此,因此您可能需要synchronize在应用程序委托中调用applicationDidEnterBackground:或注册UIApplicationDidEnterBackgroundNotification通知以执行此操作.

以下文档-[NSUserDefaults synchronize]:

因为此方法是定期自动调用的,所以只有在您无法等待自动同步时(例如,如果您的应用程序即将退出)或者您希望将用户默认值更新为磁盘上的内容,请使用此方法你没有做任何改变.

  • @Emil:错了,你可以立即再次访问密钥`name`.它已经在内存中,但尚未写入闪存. (11认同)
  • 是的,如果没有该行,您的代码将正常工作.您的设置将在稍后由iOS自动写入闪存.它将在您的应用程序最迟进入后台时编写.但要注意调试时:如果您通过按"停止"按钮终止应用程序或应用程序崩溃,则可能尚未写入设置. (5认同)
  • @MeganZhou我的猜测是Apple现在会不时进行同步,但是当进入后台时它们不会同步.现在这意味着可能发生以下情况:Apple同步用户默认值,您编写新值,app进入后台(用户默认值为_not_ synchronized),app被杀死(例如由于内存压力).现在您的新值未保存.因此,只需在应用程序进入后台时进行同步._no_需要在任何其他时间调用`synchronize`!一直_not_调用`synchronize`,它会杀死app性能. (3认同)
  • 在iOS7中,当应用程序进入后台时,我认为它不会将其写入闪存,当它在appdelegate中进入后台时必须明确同步 (2认同)

Ser*_*zha 18

你不必再写那行了.

更新文档中的方法参考

等待默认数据库的任何挂起的异步更新并返回; 此方法是不必要的,不应使用.

对该方法的评论解释了该怎么做.

     /*!
     -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
      */
     open func synchronize() -> Bool
Run Code Online (Sandbox Code Playgroud)


Les*_*ary 15

iOS 12发行说明中,您可以找到以下信息:

NSUserDefaults 有几个错误修复和改进:

删除了同步要求。不再需要使用同步、CFPreferencesAppSynchronize 或 CFPreferencesSynchronize。这些方法将在操作系统的未来版本中被弃用。

如果您的目标设备是iOS 12或更新版本,根据上述发行说明,它应该无需调用synchronize. 但是,如果您仍然支持iOS 11及更低版本,您可能仍想调用该synchronize方法。


Ant*_* MG 5

是的,使用该行,您告诉系统使用新的默认值上传NSUserDefaults.

您可以在此处找到所有信息: