This situation is a bit too elaborate to describe in mere words, so I\'ve created a minimal demo project for you to download and run:
https://github.com/mattneub/Def
I'm going to suggest this entire project is a red herring and that the problem is your testing procedure.
I theorize that UserDefaults saves slowly: it just takes a really long time for a change to UserDefaults to "take", even after every signal has occurred that the change has happened (synchronize
has returned, the didChange
notification has arrived, and so on).
Thus, I'm betting that you're just not allowing enough time between hitting the Home button and running the app again. To see that this might be so, make the following change: Instead of going directly from Step 3 to Step 4, interpose Step 3a, where you count to 10, slowly. Now the bug doesn't manifest itself.
(One could also argue that saving at willResignActiveNotification
time is just wrong. The time to save is when the relevant data changes! Thus, in the test example, we should be saving at the end of every shuffle-and-deal operation — not when the user hits the Home button.)