开发者

Accessing NSUserDefaults Often

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 obj开发者_如何学编程ect is recreated).

Is there any better way?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜