如何设置 NSUserDefault Key 的初始值?
我想为 NSUserDefault 键设置一些初始值,以便应用程序的第一次运行具有一些合理的初始设置。我以为我在应用程序包 .plist 中遇到了一种简单的方法来执行此操作,但现在我找不到它。有什么想法吗?
I want to set some initial values for my NSUserDefault keys so that the first run of the app has some reasonable initial settings. I thought I ran across a simple way to do this in the app bundle .plist, but now I can't find it. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用
NSUserDefaults
的registerDefaults
方法。在包中准备一个包含默认首选项的 plist 文件,然后使用该 plist 来注册默认值。您必须在每次启动应用程序时执行此代码。它将这些值添加到用户默认层次结构中的单独域中。每当您的应用的用户默认值未提供某个键的值时,
NSUserDefaults
将回退到此域并从那里检索值。You should use the
registerDefaults
method ofNSUserDefaults
. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.You have to execute this code on every launch of your app. It will add these values to a separate domain in the user defaults hierarchy. Whenever your app's user defaults don't provide a value for a certain key,
NSUserDefaults
will fall back to this domain and retrieve the value from there.如果您有很多默认值,请使用 ola 的答案,否则这对于一些参数很有用
If you have many default values, let use ola's answer, otherwise this is good for a few params
注意:未经测试,凭记忆完成
NB: Not tested, done from memory