Safely read-compare-write a UserDefaults value

I'm writing a utility that configures some UserDefaults values for me, such as for initializing new Macs to my personal tastes.

It reads a set of configurations from an input file. It then applies the specified preferences to various applications using the CFPreferencesSetValue API. I use it instead of NSUserDefaults, because the latter doesn't let you write to NSGlobalDomain (/Library/Preferences/.GlobalPreferences.plist).

It works well, but here's a twist: I want to be able to detect which applications have had their preferences' values actually change, and which ones already have the desired preferences in place. This allows me to automatically restart "dirty" applications such as Finder, Dock, etc. only if necessary.

I achieve that by doing this:
  1. Reading the existing preferences' values

  2. Comparing the just-read values from the desired values as read from the config file

  3. Noting down which domains have values need changing

  4. Applying the preferences changes

  5. Restarting the apps corresponding to the dirty domains.

The problem is that I have a last-write-wins scenario. Without any kind of transaction/locking mechanism, it's entirely possible that someone will change the preferences under my feet, and I'll overwrite their change. This wouldn't be an issue if I was only changing the preferences for my own app, but given that I'll be changing NSGlobalDomain (which is relatively higher "traffic"), this is a bug in waiting.

Is there a way to safely make this change, without a risk of last-write-wins clobbering other changes?
I've also asked about this on StackOverflow. It's a little niche, so understandably it didn't attract much of a crowd. Feel free to answer there for the internet points https://stackoverflow.com/q/64435545/3141234
Safely read-compare-write a UserDefaults value
 
 
Q