问题
I am creating an app that is a game where there is a need to store the high score. I believe (correct me if I'm wrong on this, but this question made it seem this way) that user defaults are the best way to accomplish this.
Sometimes when I switch between views in my app, the values change to what they previously were. Then I will switch back to another screen, and they will go back to what they should be. This happens kind-of hit and miss, so it is hard to tell, but I think it happens most after it has been set multiple times since the app was last closed; though, I know at least sometimes it only happens after they have been set once.
I have used breakpoints to ensure that the values definitely are not being changed in the code. (I did this by putting a breakpoint where all of the user defaults are set and none of them went off even though the values changed)
The only code dealing with the user defaults is as follows:
UserDefaults.standard.set(newHighScore, forKey"highScore")
-> To set the User Defaults (where newHighScore is an integer)
let highScore = UserDefaults.standarard.value(forKey: "highScore")
-> To retrieve the values
UserDefaults.standard.synchronize()
-> Every time before and after I set or retrieve values (just to play it on the safe side and because it doesn't work so I'm overly cautious)
This question suggested restarting my mac (which I did) and then doing it only in the xcode simulator. I just did that and kept the breakpoints on all the times I set the values.
I have looked at these questions and this question seems similar, but the problem doesn't apply because it was decided that it would be fixed if the code wasn't running in a playground. My code is not running in a playground.
This question also seems similar, but it doesn't apply because the values are returning as null. Mine are just changing to a value they were previously. It is also written in objective-c, so I didn't completely understand what they did to fix it. I looked through the sources it recommended for help, but didn't see anything there that helped me either.
Thanks in advance for any help on what may be my problem. I haven't been able to find anything similar to make it seem like a bug in iOS 10 or Xcode 8 beta, but I am open to any suggestions to make my code work.
来源:https://stackoverflow.com/questions/38758969/user-default-values-changing-to-previous-values-seemingly-randomly-swift