我根据这个 Apple documentation page 使用默认设置制作了自定义 plist 并借助这个answer on question在 SO。
这是我的应用委托(delegate)代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:@"defaultSettings" ofType:@"plist"];
NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
// Override point for customization after application launch.
return YES;
}
我还创建了名称为 defaultSettings .plist
的 plist,并在此处存储我的默认设置。
结构如下:
<dict>
<key>Sound</key>
<true/>
<key>Music</key>
<true/>
<key>Difficulty</key>
<integer>0</integer>
</dict>
在我的设置 VC 中,当值发生变化时,我从 plist 设置我的 outlets 和 store 到 plist。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.soundSwitcher.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Sound"];
....
self.difficultySelector.selectedSegmentIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"Difficulty"];
}
看起来不错,但 socket 没有设置为我在属性列表本身中设置的默认值。
我也无法通过 IBAction
方法更改此值
- (IBAction)switchSound:(UISwitch *)sender
{
[[NSUserDefaults standardUserDefaults] setBool:sender.isOn forKey:@"Sound"];
}
我做错了什么?
编辑: 我想提一下,如果我关闭设置 View Controller 然后再次打开它,设置会在我离开时保存。 (所以,实际上所有的工作)。但是如果我重新启动我的应用程序,所有设置都将被取消。
最佳答案
你忘记在更改 NSUserDefaults 中的内容后写这个
[defaults synchronize];
关于ios - 在 NSUserDefaults 中设置默认设置。我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22074501/