Ios 如何实现NSUserDefaults以保存首选项

Ios 如何实现NSUserDefaults以保存首选项,ios,objective-c,Ios,Objective C,我的应用程序有一个允许我关闭或打开ui声音的设置。我将其用于值: + (void)setUISoundsEnabled:(BOOL)UISoundsEnabled { __UISoundsEnabled = UISoundsEnabled; } 我的视图控制器中有一个通知,用于侦听首选项更改,然后更新声音设置 - (void)preferencesDidChange:(NSNotification *)note { NSMutableArray *changedPr

我的应用程序有一个允许我关闭或打开ui声音的设置。我将其用于值:

+ (void)setUISoundsEnabled:(BOOL)UISoundsEnabled
{
    __UISoundsEnabled = UISoundsEnabled;    
}
我的视图控制器中有一个通知,用于侦听首选项更改,然后更新声音设置

- (void)preferencesDidChange:(NSNotification *)note  
{
    NSMutableArray *changedPreferences = note.object;  
    if ([changedPreferences containsObject:@"localPlayUISounds"]) {  
        [FHSSound setUISoundsEnabled:PREFS.localPlayUISounds];  

    }
2个问题:

第一个问题:如何让PREFS中保存的设置与顶部BOOL中保存的设置相匹配

第二个问题: 如何实现NSUserDefaults来保存和加载此数据。具体来说,我在哪里实现了NSUserDefaults以保存和加载此数据。我不熟悉NSUserDefaults,因此示例将非常有用


如果您需要更多的代码或有任何问题,请告诉我,这很简单。按原样使用
NSUserDefaults
;没有必要子类化

// read the setting when you start the app
flag = [[NSUserDefaults standardUserDefaults] boolForKey:"someKey"]

// set the setting if user can change it inside your app
[[NSUserDefaults standardUserDefaults] setBool:flag forKey:"someKey"]
最好创建一个设置plist文件,以便在设置应用程序中更改这些设置。如果这样做,您还应该收听
nsUserDefaultsIDChangeNotification
,以防用户在后台更改设置应用程序中的设置

 ...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged:)
                                             name:NSUserDefaultsDidChangeNotification object:nil];

...
- (void)defaultsChanged:(id)sender {
    [[NSUserDefaults standardUserDefaults] synchronize];
    // and notify your observers as necessary based on new settings...
}
具有高级设置的应用程序通常还包含预填充的带有“初始”默认值的plist,因为在用户在应用程序设置中输入内容之前,您的
standardUserDefaults
将不包含任何值:

    NSURL *defaultSettingsURL = [[NSBundle mainBundle] URLForResource:@"DefaultSettings" withExtension:@"plist"];
    self.bundledDefaults = [NSDictionary dictionaryWithContentsOfURL:defaultSettingsURL];

您可以在第一次运行时将
bundledDefaults
转储到设置中,或者在读取用户默认值时将其作为备份使用。

以下是我在不使用NSUserDefaults的情况下解决此问题的方法

- (void)viewDidLoad
{
[super viewDidLoad];

[self setSoundPreferences];
}
通知设置为侦听prefs中的更改

- (void)preferencesDidChange:(NSNotification *)note
{
NSMutableArray *changedPreferences = note.object;
if ([changedPreferences containsObject:@"localPlayUISounds"]) {
    [FHSSound setUISoundsEnabled:PREFS.localPlayUISounds];
}
else if ([changedPreferences containsObject:@"localPlayAlertSounds"]) {
    [FHSSound setAlertSoundsEnabled:PREFS.localPlayAlertSounds];
}
最后,在启动时设置首选项

#pragma mark (launch)
- (void)setSoundPreferences
{
[FHSSound setUISoundsEnabled:PREFS.localPlayUISounds];
[FHSSound setAlertSoundsEnabled:PREFS.localPlayAlertSounds];
}

我有点困惑,
PREFS
变量从哪里来,以及您观察到什么通知并使用
preferencesDidChange:
#定义PREFS[FISettings sharedSettings]
@属性(非原子,赋值)BOOL localplayisounds我相信这就是我定义PREFS的地方。我相信这就是通知[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(PreferencesIDChange:)名称:mySharedSettingsChangedNotification对象:nil];