NSUserDefaults同步方法 [英] NSUserDefaults synchronize-method

查看:94
本文介绍了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 ?

推荐答案

[默认同步]; 是让用户默认在磁盘上立即写入 。你不需要明确调用它,iOS已经在适当的时候。所以你可以删除那行。事实上,如果每次设置默认值时调用同步,这是一个性能问题。

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不再是这种情况,所以你可能想调用同步在你的应用程序委托的 applicationDidEnterBackground:注册到 UIApplicationDidEnterBackgroundNotification 通知。

Prior to iOS 7, the user defaults where 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 synchronize]


由于此方法会定期自动调用,请仅使用此方法如果您无法等待自动同步(例如,如果您的应用程序即将退出),或者如果您要将用户默认更新为磁盘上的内容,即使您尚未进行任何更改。

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆