开发者

Observing value changes to an NSUserDefaults key

开发者 https://www.devze.com 2023-01-14 21:41 出处:网络
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.

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 addOb开发者_StackOverflow社区server 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消