Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This class is not a key value coding-compliant for the key

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.

like image 566
Carter Grycko Avatar asked Jan 22 '17 00:01

Carter Grycko


2 Answers

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")
like image 114
Mistah_Sheep Avatar answered Oct 02 '22 01:10

Mistah_Sheep


You just have to add .standard

Like UserDefaults.standard.value

You don't necessarily have to create a UserDefaults object

like image 35
Mahanaz Atiqullah Avatar answered Oct 02 '22 00:10

Mahanaz Atiqullah