简体   繁体   English

如何在Objective-C应用程序中观察命令行对NSUserDefaults的更改?

[英]How to observe command line changes to NSUserDefaults in Objective-C app?

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: 我希望我的Cocoa Objective-C应用程序能够观察到NSUserDefaults的更改,这些更改是由于默认值写法的命令行调用而导致的,例如:

defaults write <domain> <key> -array val1 val2 val3

I've poured over many examples regarding observing NSUserDefaults changes. 我已经举了很多有关观察NSUserDefaults更改的示例。 Looks like notifications are out because they only work within the same process. 似乎发出通知是因为通知仅在同一过程中起作用。 To observe command line changes, I believe that KVO is required. 为了观察命令行的变化,我相信需要KVO。

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. 在我看到的KVO示例中,我不清楚如何将“默认写...”命令行调用中使用的“域”和“键”自变量关联到用于观察那些KVO逻辑的程序结构变化。

A concise, concrete runnable example with both the code and the associated "defaults write ..." command would be greatly appreciated! 一个简洁,具体的可运行示例,其中包含代码和关联的“ defaults write ...”命令,将不胜感激!

It's just like KVOing any other change to defaults. 就像KVO将其他任何更改更改为默认值一样。

Assume your app has a CFBundleIdentifier of your.company.app , and you want to KVO a defaults value with the key foo . 假设您的应用程序具有your.company.appCFBundleIdentifier ,并且您想使用键foo KVO一个默认值。

Setup KVO of foo like so: 像这样设置foo的 KVO:

[NSUserDefaults.standardUserDefaults addObserver:self forKeyPath:@"foo" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];

and have a KVO callback method in the same class: 并在同一类中具有KVO回调方法:

-(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) 应该会导致调用KVO回调方法(已通过macOS 13,XCode9,沙盒化的默认macOS Cocoa App模板进行了测试,从AppDelegate进行了KVOing测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM