Berendschot
Berendschot

Reputation: 3114

Terminal not recognizing updated User Defaults

I'm trying to alter the save location of screenshots from within an Mac OS application, however this doesn't seem to work.

Executing the following commands in the terminal works perfect. All screenshots are saved in a folder named Screenshots (located on my desktop), just as expected.

Terminal

defaults write com.apple.screencapture location ~/Desktop/Screenshots
killall SystemUIServer

Whenever I let my application execute the following snippet, the location value in com.apple.screencapture.plist will change just as its supposed to.

Objective-C

NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"com.apple.screencapture.plist"];

[defaults setValue:@"/Users/Maarten/Desktop/Screenshots" forKey:@"location"];
[defaults synchronize];

After the value has changed, I use the terminal to run killall SystemUIServer

But somehow this command doesn't seem to work, as all screenshots are saved in its previous defined (default) location.

Upvotes: 3

Views: 635

Answers (1)

Jon
Jon

Reputation: 1489

Since 10.9 (I think), the OS caches your preferences. To invalidate the cache, you need to kill cfprefsd. So, first, set your preference via defaults then run this command:

killall -u $USER cfprefsd

After that, your preference should take without needing a restart or anything else.

Also, you can use screencapture to specify the location for a specific screenshot instead of changing the system preference. You can specify other parameters using this tool as well. Use man screencapture for more information.

Finally, from Apple's documentation, synchronize is superflous for NSUserDefaults:

synchronize

Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used.

Upvotes: 5

Related Questions