我有一个分配给NSUserDefaults对象的字符串,但是当值改变时我需要运行代码。如何使用委托检查NSUserDefaults对象值?
答案 0 :(得分:2)
嘿,您需要使用KVO (Key Value Observing)
检查NSUserDefaults
使用以下代码注册KVO
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults addObserver:self forKeyPath:@"YourValue to observer" options:NSKeyValueObservingOptionNew context:NULL];
删除'-viewDidDisappear'中的观察者
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObserver:self forKeyPath:@"YourValue to observer"];
最后实现以下方法来接收KVO通知,
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSLog(@"Output : %@ changed property %@ to value %@", object, keyPath, change);
}