如何设置NSUserDefault Keys的初始值? [英] How to set initial values for NSUserDefault Keys?
问题描述
我想为我的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?
推荐答案
你应该使用 registerDefaults
方法 NSUserDefaults的
。准备包含默认首选项的包中的plist文件,然后使用该plist注册默认值。
You should use the registerDefaults
method of NSUserDefaults
. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.
NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:@"defaultPrefs" ofType:@"plist"];
NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
您必须在每次启动应用时执行此代码。它会将这些值添加到用户默认层次结构中的单独域中。每当您的应用程序的用户默认值未提供某个键的值时, NSUserDefaults
将回退到此域并从那里检索该值。
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.
这篇关于如何设置NSUserDefault Keys的初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!