I have been developing an app that stores user data (username, etc.) between launches of the app; I stored this data in UserDefaults. However, I have recently noticed a problem: Sometimes, when I run the app, I will get some value back from UserDefaults.standard.object(forKey:)
, but other times I will get nil
when I know for a fact that there is something there.
This makes no sense to me.
I have searched for the answer to this question on SO but only found this, which did not help.
In order to test this, I made an empty app and put the following in viewDidAppear
, and then I ran the app once:
UserDefaults.standard.setValue("aValue", forKey: "aKey")
The above line is just to ensure that there is in fact a value stored. I then deleted the above line from viewDidAppear
, and then I put this in didFinishLaunchingWithOptions
:
print(UserDefaults.standard.object(forKey: "aKey") as? String)
I then ran the app 20 times. Here is my data for if the print(...)
printed nil
or "aValue"
:
✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓
It printed nil
35% of the time and it seems to me fairly random too.
I have two questions:
Why would this happen, and how can I fix/prevent it?