Accessing NSUserDefaults Often

喜夏-厌秋 提交于 2019-12-08 15:21:24

问题


During a logic process in my app, I need to access the user preferences frequently, and a bunch of times 10~15 to determine what needs to be processed and how. May this question is not about performance, but about doing it correctly.

Currently I'm doing a [[NSUserDefaults standardUserDefaults] valueForKey:...] each time I need to request a value. Is this correct? I think that "saving" the user defaults as an ivar could reduce extra work, but then I wonder if this won't have sync problems, like if the user changes the preferences and they get updated only if the app is restarted (so the user defaults object is recreated).

Is there any better way?


回答1:


Don't worry about it, it's extremely fast and I do not believe there is a better way, it's the way the class is meant to be used.

The NSUserDefaults class caches the values internally so the lookup is extremely fast. The overhead of [NSUserDefaults standardUserDefaults] vs an instance variable is so small that you wouldn't even notice it if you did it 5 million times in your code.

The only proper way of optimising this would be by improving your logic, caching the values you're using yourself with a pointer rather than the dictionary that NSUserDefaults basically is etc.




回答2:


You won't have any problem if you save the defaults object to an ivar. Notice it's a singleton and its pointer won't change.




回答3:


Do the values in the user defaults change over time during this logic process?

If not, you could access each value that you'll need throughout the process once at the start and store the results in local variables.

Then you can use those variables as many times as you like without having to hit the user defaults reading the data each time.

However, if those values are being changed while your logic process is ongoing, then accessing them from the defaults is probably the only way.

In terms of performance, accessing it 10-15 times isn't going to have any adverse effect. If you were accessing it 10-15 times per second for a prolonged period of time, then you might encounter some responsiveness issues.



来源:https://stackoverflow.com/questions/6114641/accessing-nsuserdefaults-often

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!