Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to register defaults to NSUserDefaults from multiple classes in my app?

I have read and understand the way NSUserDefaults can be used to save preferences for my app to the file system. I am also aware of the need to register defaults before using them later in the app.

What I am not sure of, however, is if it is okay to register defaults from various classes in my app. For example, in the AppDelegate I want to register a preference that belongs to the entire app, but in a Theme-class I want to use (and therefore register) preferences only used for getting and setting the app's theme. More classes will have their own needs as far as user defaults go, so this applies to multiple parts of any project I work on.

Is this way of keeping the preferences with the classes they belong to the correct way of working?

like image 990
Richard Altenburg - Brainchild Avatar asked Oct 04 '12 18:10

Richard Altenburg - Brainchild


3 Answers

Yes, you can register defaults from multiple classes. When you register a new default, it just adds that new key/value pair to the registration domain (there is only one of those for the app). I think the way you're doing it is quite reasonable.

like image 61
rdelmar Avatar answered Oct 17 '22 12:10

rdelmar


The NSUserDefaults are related to the entire application. So, it's not important where you read/store them: the keys will be visible to any class even when they're set in another.

I personally try to use my own schemes, so related preferences could be "close".

i.e:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:themePreferences forKey:@"Theme"];
[defaults setObject:otherPreferences forKey:@"Other"];

Hope it helps.

like image 2
NovaOverflow Avatar answered Oct 17 '22 12:10

NovaOverflow


This isn't necessary, but if you wanted to zone your preferences file by class, you could include the class name as part of the key. For example:

NSString *prefKey = [ NSString stringWithFormat: @"%s.prefName", (const char *) class_getName([ self class ]) ];

Where prefName is the name of whatever preference you're storing. That way you could use the same preference name with different classes, and not worry about them overwriting one another. But as others have said, unless you have a specific need to do this, NSUserDefaults can be called from anywhere in the application.

like image 1
Jonathan Zdziarski Avatar answered Oct 17 '22 13:10

Jonathan Zdziarski