Reputation: 450
I'd like my Cocoa Objective-C app to observe NSUserDefaults changes that are a result of a command line invocation of defaults write such as:
defaults write <domain> <key> -array val1 val2 val3
I've poured over many examples regarding observing NSUserDefaults changes. Looks like notifications are out because they only work within the same process. To observe command line changes, I believe that KVO is required.
In the KVO examples I've seen, it's not clear to me how to associate the "domain" and "key" arguments used in the "defaults write ..." command line call to the programmatic constructs of KVO logic used to observe those changes.
A concise, concrete runnable example with both the code and the associated "defaults write ..." command would be greatly appreciated!
Upvotes: 0
Views: 558
Reputation: 622
It's just like KVOing any other change to defaults.
Assume your app has a CFBundleIdentifier
of your.company.app, and you want to KVO a defaults value with the key foo.
Setup KVO of foo like so:
[NSUserDefaults.standardUserDefaults addObserver:self forKeyPath:@"foo" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
and have a KVO callback method in the same class:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
// just for debugging:
NSLog(@"KVO: keyPath = '%@', change = %@", keyPath, change);
}
Build and run the app; then, on the command line, issue:
defaults write your.company.app foo "bar"
should result in the KVO callback method being called (tested with macOS 13, XCode9, sandboxed default macOS Cocoa App template, KVOing from AppDelegate)
Upvotes: 2