Best Practice for NSUserDefaults synchronize

2019-02-03 23:08发布

问题:

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?

回答1:

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.



回答2:

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.

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.