观察 NSUserDefaults 键的值更改
我对保存在 NSUserdefaults 中的特定键的值变化感兴趣。然而,我所拥有的并不适合我。 observeValueForKeyPath 不会被触发。
更新:我想我已经发现了这个问题。如果我使用字符串,而不是使用定义的常量,那么它就会被触发。
[[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");
}
}
不理想,但如果我在 addObserver 行之前加上:
NSString* keyToObserve = kSomethingInteresting;
并在 addObserver 行中使用它,那么就可以了。看起来有点繁琐?
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");
}
}
Not ideal but if I precede the addOberver line with:
NSString* keyToObserve = kSomethingInteresting;
And use that in the addObserver line then that works. Seems a bit fiddly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,在本例中以及在所有需要观察用户默认值中某些内容的情况下,我将放弃使用定义的常量。遗憾的是,因为我喜欢在整个过程中使用它们作为关键名称。
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.