It seems like the UserDefaults or at least the shared group UserDefaults is being cached somewhere, and it can put you in a confused debugging state.
To highlight what I meant, create 2 sandboxed apps with the same app group, i.e: com.gietal.sandbox.group
On the first app, do the following:
To highlight what I meant, create 2 sandboxed apps with the same app group, i.e: com.gietal.sandbox.group
On the first app, do the following:
// App 1 if let defaults = UserDefaults(suiteName: "com.gietal.sandbox.group") { defaults.set(123, forKey: "myKey") }
When you run the first app, it should create this file ~/Library/Group Containers/com.gietal.sandbox.group/Library/Preferences/com.gietal.sandbox.group.plist where the setting "myKey = 123" is stored as xml.
Now on the second app, try to read the value from the shared group UserDefaults. At this point, it should return the expected value of 123
Now on the second app, try to read the value from the shared group UserDefaults. At this point, it should return the expected value of 123
// App 2 if let defaults = UserDefaults(suiteName: "com.gietal.sandbox.group") { let value = defaults.value(forKey: "myKey") print("value: \(value)") }
Now delete the plist file ~/Library/Group Containers/com.gietal.sandbox.group/Library/Preferences/com.gietal.sandbox.group.plist
And try reading the value again from app 2. You would be surprised that it would still returns 123 instead of the expected nil.
However, if you reboot your mac and try reading the value of "myKey" from app 2 again, it will correctly returns nil this time!
So this made me believe that UserDefaults is being cached somewhere in the system and could get out of sync with the actual plist file where the values are stored.
And try reading the value again from app 2. You would be surprised that it would still returns 123 instead of the expected nil.
However, if you reboot your mac and try reading the value of "myKey" from app 2 again, it will correctly returns nil this time!
So this made me believe that UserDefaults is being cached somewhere in the system and could get out of sync with the actual plist file where the values are stored.