macOS UserDefaults auto-populates older after deleting and saving data

Saving data first time in UserDefaults on macOS creates a plist file at Containers folder path but after deleting and saving different data next time, previuos data(before deleting the app folder) also populates in plist file.

if let test = UserDefaults(suiteName: "my_test_app_userdefaults_suite") { test.setValue("opt_in_1", forKey: "email_1") test.setValue("opt_in_2", forKey: "email_2") test.setValue("opt_in_3", forKey: "email_3") test.synchronize() }

Steps:

  1. Run the macOS app with above source code, which saves key-value pairs in UserDefaults.
  2. Checked the UserDefaults plist at path /Users/rahulmahajan/Library/Containers/com.TestuUserDefaults/Data/Library/Preferences/my_test_app_userdefaults_suite.plist and all the data is available there, which is good.
  3. Now, deleted the app folder at path /Users/rahulmahajan/Library/Containers/com.TestuUserDefaults.
  4. Commented the opt_in_2 and opt_in_3 statements, ran the app.
  5. Checked the plist at path from Step-2, the lines commented in Step-4 are auto-populated in plist.

The title of the post is,

macOS UserDefaults auto-populates older entries after deleting and saving data on next launch of the macOS app.

User defaults are cached, so if you want to remove them and clear the cache use the defaults cli command.

macOS UserDefaults auto-populates older after deleting and saving data
 
 
Q