I know this question has been asked many times, but all of the situations seem to be different then mine and I do not have the ability to comment.
I am trying to learn how to make a UserDefault variable, but it keeps crashing. The error I am getting in the logs is:
*** Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<NSUserDefaults 0x1097d6bf8> valueForUndefinedKey:]: this class is
not key value coding-compliant for the key AmountOfCoins.'
Here is all the times the UserDefault was used in my code:
class GameScene: SKScene, SKPhysicsContactDelegate {
var CoinCount = Int()
^Here I defined a variable to make accessing the coin count easier.
override func didMove(to view: SKView) {
if let x = UserDefaults.value(forKey: "AmountOfCoins") as? Int{
CoinCount = x
}
^ This was used to check if the AmountOfCoins was empty. I think I may have made a mistake here.
func startGame() {
score = 0
CoinCount = UserDefaults.value(forKey: "AmountOfCoins") as! Int
scoreview.text = "\(score)"
coinview.text = "\(UserDefaults.value(forKey: "AmountOfCoins"))"
}
^ Here is a function that is called when the game is started
func addCoin(){
run(SKAction.playSoundFileNamed("Coin.wav", waitForCompletion: false))
CoinCount += 1
UserDefaults.standard.set(CoinCount, forKey: "AmountOfCoins")
scoreview.text = "\(UserDefaults.value(forKey: "AmountOfCoins"))"
coinview.text = "\(CoinCount)"
^ And lastly here is a function that is called whenever a coin needs to be added.
I have read a few different methods for fixing this error but I really don't understand how exactly it works.
As people have said in the comments above, it should be something like this
let defaults = UserDefaults.standard
defaults.value(forKey: "AmountOfCoins")
instead of
UserDefaults.value(forKey: "AmountOfCoins")
You just have to add .standard
Like UserDefaults.standard.value
You don't necessarily have to create a UserDefaults object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With