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]:
因为此方法是定期自动调用的,所以只有在您无法等待自动同步时(例如,如果您的应用程序即将退出)或者您希望将用户默认值更新为磁盘上的内容,请使用此方法你没有做任何改变.
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方法。
是的,使用该行,您告诉系统使用新的默认值上传NSUserDefaults.
您可以在此处找到所有信息:
| 归档时间: |
|
| 查看次数: |
34695 次 |
| 最近记录: |