观察值更改为NSUserDefaults项 [英] Observing value changes to an NSUserDefaults key
问题描述
我对保存在NSUserdefaults中的特定键的值更改感兴趣.但是,我所拥有的对我不起作用. watchValueForKeyPath不会被触发.
I'm interested in the value change of a particular key which I keep in NSUserdefaults. However, what I have is not working for me. observeValueForKeyPath does not get triggered.
更新:我想我已经发现了问题.如果我使用字符串,则将其触发,而不是使用已定义的常量.
Update: I think I've discovered the issue. Rather than using a defined constant, if I use a string then it gets fired.
[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:kSomethingInteresting options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"Defaults changed, %@.%@", object, keyPath);
if ((object == [NSUserDefaults standardUserDefaults]) && [keyPath isEqualToString:kSomethingInteresting]) {
NSLog(@"kSomethingInteresting changed in defaults");
}
}
不太理想,但是如果我在addOberver行之前加上:
Not ideal but if I precede the addOberver line with:
NSString* keyToObserve = kSomethingInteresting;
然后在addObserver行中使用它,然后就可以了.看起来有点古怪?
And use that in the addObserver line then that works. Seems a bit fiddly?
推荐答案
因此,在这种情况下以及在需要观察用户默认值的所有情况下,我将放弃使用已定义的常量.真可惜,我喜欢在整个过程中使用它们作为键名.
So I'm going to scrap the use of a defined constant in this instance and in all instances where I need to observe something in userdefaults. Shame, as I like using them for key names throughout.
这篇关于观察值更改为NSUserDefaults项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!