在vc1
我设置BOOL
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"myKey"];
在vc2
我希望观察BOOl
是否更改[[NSUserDefaults standardUserDefaults] boolForKey:@"myKey"]
在这里查看 Add Observer to BOOL variable 和 Registering a bool for a NSNotification
似乎都不适合我的模式
答案 0 :(得分:1)
使用下面的代码,当BOOL
值发生变化时,它会调用。您可以使用 KVO 来观察myKey
的值。在您观察的任何课程中写这个值。在viewDidLoad
vc2
中写入
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults addObserver:self
forKeyPath:@"myKey"
options:NSKeyValueObservingOptionNew
context:NULL];
在您已在vc2
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
//check here if it is myKey than do something
if([keyPath isEqualToString:@"myKey"]){
//do your work
NSLog(@"KVO: %@ changed property %@ to value %@", object, keyPath, change);
BOOL newValue = [[change objectForKey: NSKeyValueChangeNewKey] boolValue];
}
else{
NSLog(@"Not my key");
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
在vc2
dealloc
-(void)dealloc{
[[NSUserDefaults standardUserDefaults] removeObserver:self forKeyPath:@"myKey"];
}
在observeValueForKeyPath
中检查myKey
的值是否更改,而不是根据需要进行更改。
答案 1 :(得分:0)
注册NSUserDefaultsDidChangeNotification
并在通知触发时检查您的用户默认值,以查看更改的值是否是您感兴趣的值。