1

I am trying to test changes to my UserDefaults after using defaults write on the command line.

If in swift I write:

UserDefaults.standard.set("Hello", forKey:"test")

and on the command line I enter:

defaults read ~/Library/Containers/[app]/Data/Library/Preferences/[app].plist test

where [app] is my application, the result is correct.

If, how ever, I then enter:

defaults write ~/Library/Containers/[app]/Data/Library/Preferences/[app].plist test "Goodbye"

and in swift:

print("Test: \(UserDefaults.standard.string(forKey: "test"))")

The change seems to be ignored. Using defaults read does give the new value.

What is missing her?

Running on am iMac with MacOS 10.15.6 and XCode 11.7. I am using sandboxing, and the location was obtained from the SO question Where is a Mac Application's NSUserDefaults Data Stored? .

Manngo
  • 14,066
  • 10
  • 88
  • 110

2 Answers2

0

If you are making any changes in the [app].plist through defaults write command then your changes will reflect in your next run. So after making changes run your application again on iOS Simulator.

Please be noted that your Library path will change on every run. Use the following line of code to get the library path:

Swift Code:

let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
print("Your UserDefaults are stored in this folder: \(libraryPath)/Preferences")
MilanPanchal
  • 2,943
  • 1
  • 19
  • 37
0

It appears that this a caching issue.

There is a discussion at http://hints.macworld.com/article.php?story=20130908042828630 , and a reply by someone called jgj, largely ignored by the rest of the discussion has this little gem:

killall cfprefsd

It works perfectly. I now use:

defaults write … ; killall cfprefsd

and everything works smoothly.

Manngo
  • 14,066
  • 10
  • 88
  • 110