且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NSUserDefaultsDidChangeNotification:密钥的名称是什么,改变了什么?

更新时间:2023-11-20 19:49:28

正如其他人所述,无法从NSUserDefaultsDidChange通知中获取有关已更改密钥的信息。但是没有必要复制任何内容并自行检查,因为键值观察(KVO)也适用于NSUserDefaults,如果您需要具体是通知某个属性

As others stated, there is no way to get the info about the changed key from the NSUserDefaultsDidChange Notification. But there is no need to duplicate any content and check for yourself, because there is Key Value Observing (KVO) which also works with the NSUserDefaults, if you need to specifically be notified of a certain property:

首先,注册KVO而不是使用NotificationCenter:

First, register for KVO instead of using the NotificationCenter:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults addObserver:self
           forKeyPath:@"nameOfThingIAmInterestedIn"
              options:NSKeyValueObservingOptionNew
              context:NULL];

不要忘记删除观察(例如在viewDidUnload或dealloc中)

don't forget to remove the observation (e.g. in viewDidUnload or dealloc)

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObserver:self forKeyPath:@"nameOfThingIAmInterestedIn"];

并最终实施此方法以接收KVO通知

and finally implement this method to receive KVO notifications

-(void)observeValueForKeyPath:(NSString *)keyPath 
                 ofObject:(id)object
                   change:(NSDictionary *)change
                  context:(void *)context 
{
    NSLog(@"KVO: %@ changed property %@ to value %@", object, keyPath, change);
}