Why use registerDefaults: instead of setValue:forKey:?

▼魔方 西西 提交于 2020-01-29 04:05:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9166468/why-use-registerdefaults-instead-of-setvalueforkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!