本文介绍了NSUserDefaults 同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

[defaults synchronize];

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

I need to know why do i have to use the last line of the above code [defaults synchronize] ? What is the purpose of using it? Is it a must ?

推荐答案

[default synchronize]; 的目的是让用户的默认设置立即写入磁盘.你不需要显式调用它,iOS 已经在适当的时候这样做了.所以你可以删除那条线.事实上,如果每次设置默认值都调用synchronize,这是一个性能问题.

The purpose of [default synchronize]; is to make the user defaults get written on disk immediately. You don't need to call it explicitly, iOS already does it at appropriate moments. So you can remove that line. In fact, it's a performance problem if you call synchronize every time you set a default.

在 iOS 7 之前,当应用程序转换到后台时,用户默认设置总是同步的.从 iOS 7 开始,情况不再如此,因此您可能希望在应用程序委托的 applicationDidEnterBackground: 中调用 synchronize 或注册到 UIApplicationDidEnterBackgroundNotification> 通知这样做.

Prior to iOS 7, the user defaults were always synchronized when the application transitioned into background. As of iOS 7, that is no longer the case, so you might want to call synchronize in your app delegate's applicationDidEnterBackground: or register to the UIApplicationDidEnterBackgroundNotification notification to do that.

来自 -[NSUserDefaults同步]的文档:

From the documentation for -[NSUserDefaults synchronize]:

由于此方法会定期自动调用,因此仅当您无法等待自动同步时(例如,如果您的应用程序即将退出)或者您想更新用户默认设置为启用的内容时才使用此方法即使您没有进行任何更改,磁盘也是如此.

这篇关于NSUserDefaults 同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:35