Observing value changes to an NSUserDefaults key

南楼画角 提交于 2019-12-07 14:01:10

问题


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?


回答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.



来源:https://stackoverflow.com/questions/3633973/observing-value-changes-to-an-nsuserdefaults-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!