【发布时间】:2016-03-24 04:54:01
【问题描述】:
这可能是 iOS 9.3(发行版)中的一个严重错误。
在向[NSUserDefaults standardUserDefaults] 添加单个观察者时,我注意到响应方法-observeValueForKeyPath:ofObject:change:context: 被多次调用。
在下面的简单示例中,每按下一次 UIButton,observeValueForKeyPath 就会触发两次。在更复杂的示例中,它会触发更多次。它仅存在于 iOS 9.3(sim 卡和设备上)。
这显然会对应用造成严重破坏。其他人有同样的经历吗?
// ViewController.m (barebones, single view app)
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"viewDidLoad");
[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"SomeKey" options:NSKeyValueObservingOptionNew context:NULL];
}
- (IBAction)buttonPressed:(id)sender {
NSLog(@"buttonPressed");
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"SomeKey"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
NSLog(@"observeValueForKeyPath: %@", keyPath);
}
【问题讨论】:
-
NSUserDefaults 键值是否可观察?我没有看到任何证据表明它是。你正在做一些你没有理由去做的事情。如果它停止工作,你不能抱怨。
-
@matt 我没有考虑到这一点。然而,我在 NSUserDefaults.h 中发现了以下内容:
NSUserDefaults can be observed using Key-Value Observing for any key stored in it. -
@Matt,我在看同一个
NSUserDefaults.h吗?我找不到您在此标题中发布的评论。 -
@BorisVerebsky 你在检查什么版本的 Xcode?也许它是 Xcode 7.3/iOS 9.3 中的新功能。
-
@Matt,XCode 7.2,将仔细检查 XCode 7.3/iOS 9.3
标签: ios objective-c key-value-observing ios9.3