Reputation: 2503
This is a simple task from the terminal:
defaults delete -g <key>
I'd like to do this in Swift using NSUserDefaults
. The documentation says:
If you want to change the value of a preference in the global domain, write that same preference to the application domain with the new value.
This simply sets a new value for the same key in the application domain so that when NSUserDefaults
retrieves the value for the key in the future, it will find the new value in the application domain before it searches the global domain.
Is there some way to either:
using NSUserDefaults
?
I know I can use NSTask, for example, to run defaults delete -g <key>
, but I consider that a workaround (a valid one).
Upvotes: 2
Views: 1061
Reputation: 90531
You can try this, but it's not really a good idea:
var defaults = NSUserDefaults.standardUserDefaults()
var globalDomain = defaults.persistentDomainForName(NSGlobalDomain)
globalDomain.removeObjectForKey(someKey)
defaults.setPersistentDomain(globalDomain, forName:NSGlobalDomain)
The main problem is a race condition with other processes or threads. If something changes the global domain between the time you read it and when you write it back, you undo those changes, even if they didn't involve the key you were manipulating. Also, you're potentially reading and writing a large dictionary, doing a lot more work than actually necessary.
Probably better to drop down to the CFPreferences
API:
CFPreferencesSetValue(someKey, nil, kCFPreferencesAnyApplication,
kCFPreferencesCurrentUser, kCFPreferencesCurrentHost)
Upvotes: 5