简体   繁体   English

如何检测NSUserDefault中的更改?

[英]How to detect changes in NSUserDefault?

I have switches and I want to detect if any of switch was changed position, if changes was made I need to start my action. 我有开关,我想检测是否有任何开关的位置改变了,如果进行了改变,我需要开始行动。

Switches stores position in NSUserDefaults 切换NSUserDefaults存储位置

- (IBAction)saveSwitch:(id)sender
{     
    NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults];
    [defs1 setBool: blackSwitch.on forKey: @"blackKey"];

    NSUserDefaults *defs2 = [NSUserDefaults standardUserDefaults];
    [defs2 setBool: greenSwitch.on forKey: @"greenKey"];

    [[NSUserDefaults standardUserDefaults] synchronize];
}

You can post a notification whenever you call synchronize 您可以在每次调用synchronize时发布通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyAppSettingsChanged" object:self userInfo:nil];

Then in your other class listen to the notification. 然后在您的另一堂课中收听通知。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppSettingsChanged:) name:@"MyAppSettingsChanged" object:nil];

-(void) onAppSettingsChanged:(NSNotification)notification
{
   // settings changed
}

If you want, you can pass an NSDictionary into userInfo when calling postNotificationName that contains information like which settings have changed. 如果需要,可以在调用postNotificationName时将NSDictionary传递给userInfo,其中包含诸如已更改设置的信息。

If you're using NSUserDefaults the easiest is to subscribe NSUserDefaultsDidChangeNotification . 如果您使用的是NSUserDefaults,最简单的方法是订阅NSUserDefaultsDidChangeNotification It is automatically sent when something changes. 更改时会自动发送。

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

The best way to track changes to NSUserDefaults is to add an observer using KVO. 跟踪对NSUserDefaults更改的最佳方法是使用KVO添加观察者。 This way you do not need to perform any custom notification code or track changes manually. 这样,您无需执行任何自定义通知代码或手动跟踪更改。

In the class that wants to be informed about the changes just register it as a listener to the specified keys: 在要通知有关更改的类中,只需将其注册为指定键的侦听器即可:

[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"blackKey" options:NSKeyValueObservingOptionNew context:nil];    
[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"greenKey" options:NSKeyValueObservingOptionNew context:nil];

Then just respond to the notification: 然后只需响应通知:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (object == defaults) {
         // Here you can grab the values or just respond to it with an action.
    }
}

Now whenever one of those keys changes you will be notified automatically. 现在,只要其中一个键发生更改,您就会自动收到通知。

This is a super clean solution and allows for some heavy reuse. 这是一个超级干净的解决方案,可以大量重用。 For example, if you add the NSKeyValueObservingOptionInitial key to the options parameter above ( NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew ) then it will also notify your observer method with the initial value, allowing you to reuse that method even for initial states. 例如,如果将NSKeyValueObservingOptionInitial键添加到上述options参数( NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew ),则它还将用初始值通知观察者方法,从而即使在初始状态下也可以重用该方法。


Swift Version 迅捷版

Setting up the defaults: 设置默认值:

NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: "blackKey", options: .New, context: nil)
NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: "greenKey", options: .New, context: nil)

The observer: 观察者:

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if object is NSUserDefaults {
        // Here you can grab the values or just respond to it with an action.
    }
}

You cannot detect changes in NSUserDefaults. 您无法在NSUserDefaults中检测到更改。 Instead, track when the switch itself is changed, and handle that event. 相反,跟踪开关本身何时更改,并处理该事件。 Example: 例:

[blackSwitch addTarget:self
                action:@selector(blackSwitchChanged:) 
      forControlEvents:UIControlEventValueChanged];

Handle the switch position changing: 处理开关位置变化:

- (IBAction)blackSwitchChanged:(id)sender {
    NSLog(@"Black switch changed");
    ..
    // check if blackSwitch is on or off.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM