Skip to content

Instantly share code, notes, and snippets.

@salexkidd
Last active January 22, 2018 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salexkidd/67fc3b780482484fefbead3518c0a97e to your computer and use it in GitHub Desktop.
Save salexkidd/67fc3b780482484fefbead3518c0a97e to your computer and use it in GitHub Desktop.
observeValueForKeyPathが二度呼ばれてしまう問題...
#import "AppDelegate.h"
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
// Remove All Preferences settings.
[userDefault removePersistentDomainForName: [[NSBundle mainBundle] bundleIdentifier]];
// Set Default value to UserDefaults
[userDefault registerDefaults:@{@"test":@NO,}];
// Observing "testValue"
[userDefault addObserver:self
forKeyPath:@"testValue"
options:NSKeyValueObservingOptionNew
context:nil];
// after change, call observeValueForKey...
[userDefault setBool:YES forKey:@"testValue"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"Why call twice!?!?");
}
// 2018-01-22 20:55:43.658261+0900 KVOTestForObjC[22625:762757] Why call twice!?!?
// 2018-01-22 20:55:43.658357+0900 KVOTestForObjC[22625:762757] Why call twice!?!?
@end
@salexkidd
Copy link
Author

NSUserDefaultの値をKVOで見張り、値を変更すると何故か二度変更の通知が飛んできてしまう問題。
何が原因だか今のところ不明。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment