Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use registerDefaults: instead of setValue:forKey:?

When I'm setting up the default preferences for my app, I'm doing the following:

1) Reading Root.plist from inside Settings.bundle into a dictionary.

2) I test if a preference is set, and if not I'm registering my defaults dictionary via [NSUserDefaults standardUserDefaults] registerDefaults:]

Problem is, defaults registered with registerDefaults: do not go to the persistent store, so if the user never changes their preferences I am reading my default preferences and registering them with NSUserDefaults every time the app launches.

Instead of using registerDefaults: I could use setValue:forKey: and have my default setting go to the persistent store, bypassing the need to build & register a dictionary on each launch. However, Apple's documentation and sample code both point to registerDefaults:.

So I'm trying to figure out when and why I should use registerDefaults: and when/why I should use setValue:forKey: instead?

like image 573
gabrielk Avatar asked Feb 06 '12 20:02

gabrielk


1 Answers

Problem is, defaults registered with registerDefaults: do not go to the persistent store, so if the user never changes their preferences I am reading my default preferences and registering them with NSUserDefaults every time the app launches.

Yes. Why is that a problem? Why write to disk things you have in the code already?

Instead of using registerDefaults: I could use setValue:forKey: and have my default setting go to the persistent store, bypassing the need to build & register a dictionary on each launch. However, Apple's documentation and sample code both point to registerDefaults:.

Only if you first checked "is this value set? No? OK, now set it." That's more code and cost than just using registerDefaults:.

You should use registerDefaults: to set the defaults. You should use setValue:forKey: to save values that are actively set.

Remember also that NSUserDefaults exists on Mac as well. There, the user can directly access the settings with the defaults command, so the program is not the only entity that can modify this store.

like image 179
Rob Napier Avatar answered Oct 21 '22 17:10

Rob Napier