Programmatic Equivalent of “defaults write” comman

2020-03-04 09:02发布

问题:

Trying programmatically do what the 'defaults write' command does in OS X. I can't seem to figure out how to get the correct preferences dictionary for the domain I'm looking for. I can get some preferences for the domains in the code below, but the preferences in question don't seem to be in the dict.

Why/How are they in the terminal command but not in the code? Are they not in the standard user defaults? Just can't seem to find them.

Edit: these are the commands I'm trying to put into code:

defaults write com.apple.dock mcx-expose-disabled -bool true
defaults write com.apple.dashboard mcx-disabled -bool true




NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSMutableDictionary   *dockDict = [[defaults persistentDomainForName:@"com.apple.dock"] mutableCopy];
NSMutableDictionary   *dashDict = [[defaults persistentDomainForName:@"com.apple.dashboard"] mutableCopy];

[dockDict setValue:YES forKey:@"mcx-expose-disabled"];


[defaults setPersistentDomain:dockDict forName:@"com.apple.dock"];
[defaults setPersistentDomain:dashDict forName:@"com.apple.dashboard"];

回答1:

The only problem is your line here:

 [dockDict setValue:YES forKey:@"mcx-expose-disabled"];

This should be

 [dockDict setValue:[NSNumber numberWithBool:YES] forKey:@"mcx-expose-disabled"];

Objective-C doesn't "auto-box" values of primitive types into objects.

And, the compiler should have given you a warning saying that you can't pass YES to setValue:forKey:. You should inspect every warning the compiler emits! That's what the warnings are for!



回答2:

It might be easier to use Core Foundation for this, e.g.,

CFPreferencesSetAppValue( CFSTR("mcx-expose-disabled"), kCFBooleanTrue, CFSTR("com.apple.dock") );
CFPreferencesAppSynchronize( CFSTR("com.apple.dock") );