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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With