Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 object is recreated).

Is there any better way?

like image 510
sidyll Avatar asked May 24 '11 17:05

sidyll


1 Answers

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.

like image 64
Antwan van Houdt Avatar answered Sep 29 '22 11:09

Antwan van Houdt