问题描述
当UserDefaults中的某些值发生变化时,此代码将调用方法defaultsChanged
This code will call the method "defaultsChanged", when some value in UserDefaults changed
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(defaultsChanged:)
name:NSUserDefaultsDidChangeNotification
object:nil];
此代码将为我提供更改的价值
This Code will give me the VALUE that changed
- (void)defaultsChanged:(NSNotification *)notification {
// Get the user defaults
NSUserDefaults *defaults = (NSUserDefaults *)[notification object];
// Do something with it
NSLog(@"%@", [defaults objectForKey:@"nameOfThingIAmInterestedIn"]);
}
但是如何才能获得密钥的名称? / p>
but how can I get the NAME of the key, that changed??
推荐答案
正如其他人所述,无法从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);
}
这篇关于NSUserDefaultsDidChangeNotification:密钥的名称是什么,改变了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!