在同步完成之前,iOS NSUserDefaults访问 [英] iOS NSUserDefaults access before synchronize completion

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

问题描述

如果我设置 NSUserDefault 对象并尝试在同步之前访问它,我是否可以访问该对象添加?

If I set an NSUserDefault object and try to access it before it has been synchronized, will I be able to access the object I just added?

我尝试编写代码来测试它,但我不确定同步是否在我不知情的情况下发生。

I've tried writing code to test it but I'm unsure of if the synchronization is happening without me knowing it.

推荐答案

是的,您的应用程序可以在同步发生之前访问已保存的首选项,如果在应用程序的同一运行会话期间在读取周期发生之前保存它。为了在后续应用程序启动期间访问信息,必须进行同步。

Yes, your application can access the saved preferences before the synchronize happens, if it is saved before the read cycle happens during the same run session of the application. For accessing the information during subsequent app launches it is necessary that the synchronisation happens.

来自Apple文档:NSUserDefaults

From the Apple docs: NSUserDefaults


NSUserDefaults缓存信息,以避免每次需要默认值时都必须打开用户的默认数据库。 synchronize方法会定期自动调用,使内存缓存与用户的默认数据库保持同步。

NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database.

synchronize 方法将对内存缓存的任何修改写入磁盘( Library / Preferences 中的plist文件),并将未修改的内存缓存更新为最新在磁盘上。此方法会定期调用,而不会通知应用程序。

The synchronize method writes any modifications to in-memory cache to the disk (plist file in Library/Preferences) and updates the unmodified in-memory cache to the latest on disk. This method gets invoked at periodic intervals, without the app getting notified.

再次从文档: [NSUserDefaults synchronize]


讨论

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

Discussion
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.

根据我的经验,当应用程序要退出时,显式调用 synchronize 方法,这可确保在下次启动时可以使用最新的首选项。但是,我还遇到了在 synchronize 发生之前应用程序崩溃的情况,因此不存储pref。您的应用程序必须能够处理这些方案。

In my experience, call the synchronize method explicitly when application is going to exit, this ensures that the latest preferences are available on next launch. However, I have also come across scenarios when application crashes before the synchronize happens so the pref are not stored. Your application must be able to handle these scenarios.

附加

使用NSUserDefaults存储最少的数据,不存储大量数据。原因是,在应用程序启动期间加载应用程序默认值,如果要加载的数据很大,那么应用程序加载时间会增加,并且可能是应用程序被 Springboard杀死

这篇关于在同步完成之前,iOS NSUserDefaults访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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