xcode NSUserDefaults 同步的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5600859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:45:59  来源:igfitidea点击:

Best Practice for NSUserDefaults synchronize

iphonexcodensuserdefaults

提问by Lauren Quantrell

I'm using [[NSUserDefaults standardUserDefaults] synchronize]each time I write anything to the plist. Is that overkill? Or are there adverse effects in doing this?

我使用的是[[NSUserDefaults standardUserDefaults] synchronize]每次我写东西的plist中。这是矫枉过正吗?或者这样做是否有不利影响?

回答by Joe

Yes it may be overkill but in a simple application will you notice a performance hit? probably not if you are only saving after basic user interaction such as the user selecting their settings. The benefit to calling synchronize more often is if your application may crash and the information you are saving is important, otherwise iOS will save it for you periodically.

是的,这可能有点矫枉过正,但在一个简单的应用程序中,您会注意到性能下降吗?如果您仅在基本用户交互(例如用户选择其设置)之后保存,则可能不会。更频繁地调用同步的好处是如果您的应用程序可能会崩溃并且您保存的信息很重要,否则 iOS 会定期为您保存它。

回答by Koushik Ravikumar

The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user's defaults database.

以定期间隔自动调用的同步方法使内存缓存与用户的默认数据库保持同步。

Calling it frequently may cause performance issues, but it's not an overkill if it's a small application (like already mentioned) OR if you really need your plist to be up to date with the changes made in the current thread or changes made in some other thread in the application.

频繁调用它可能会导致性能问题,但如果它是一个小应用程序(就像已经提到的那样)或者如果你真的需要你的 plist 与当前线程中所做的更改或其他一些线程中所做的更改保持同步,这并不是一种矫枉过正在应用程序中。

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

由于此方法会定期自动调用,因此仅当您无法等待自动同步时(例如,如果您的应用程序即将退出)或如果您想将用户默认更新为磁盘上的内容,即使你没有做任何改变

Probably the only adverse effect you might notice is a negligible decrease in performance.

您可能会注意到的唯一不利影响可能是性能下降可忽略不计。