-4

//Help Please This Code won't work, getting this as feedback from Xcode. fatal error: unexpectedly found nil while unwrapping an Optional value


    var savedScore = NSUserDefaults.standardUserDefaults().objectForKey("HighestScore") as! Int

import SpriteKit

class GameScene: SKScene {

    var highestScore:Int = 2
    var score = Int()

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */

        //To save highest score

        //To get the saved score
        var savedScore = NSUserDefaults.standardUserDefaults().objectForKey("HighestScore") as! Int

        print(savedScore)


    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */
        score += 1
        print("Score - \(score)")

        if score > highestScore
        {
            highestScore = score
            NSUserDefaults.standardUserDefaults().setObject(highestScore, forKey:"HighestScore")
            NSUserDefaults.standardUserDefaults().synchronize()
            print("Beat")
        }

        else {
            print("Not Beat")
        }

    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}
Matt
  • 74,352
  • 26
  • 153
  • 180
Amen Parham
  • 73
  • 1
  • 8
  • Welcome to Stack Overflow! Please do not edit your question to include a new problem. Instead, create a new question. – Matt Apr 27 '16 at 18:33
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Mar 19 '18 at 06:03

3 Answers3

1

You are calling the userDefaults function before it ever saves. You need to check if it exists. First you can make it easier on yourself and just save it as an integer. Then you need to check to see if there is a value.

NSUserDefaults.standardUserDefaults().setInteger(highestScore, forKey: "HighestScore")

//IntegerForKey will never return nil.  This will return 0 if there is no value.
let savedScore = NSUserDefaults.standardUserDefaults().integerForKey("HighestScore") 
print(savedScore)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
rmickeyd
  • 1,551
  • 11
  • 13
0

NSUserDefaults.standardUserDefaults is a Dictionary Object. If you try to read a value that has not set value before, you will get a nil. You could check if the value for key exist

let savedScore = NSUserDefaults.standardUserDefaults.integerForKey("HighestScore") ?? 0

Then if value for HighestScore exist, you will get the correct value, if not, you will set 0 as default value for savedScore.

BrikerMan
  • 334
  • 1
  • 6
  • Im new to Stackflow so sorry if i checked your comment as a negative but thanks for your help. I'm trying to fix it right now with both of you and rMickeyD's help – Amen Parham Apr 22 '16 at 04:55
  • I did what what you suggested and it works with no errors but now it doesn't save the high score when i leave the app and open it up again – Amen Parham Apr 22 '16 at 05:19
  • try `NSUserDefaults.standardUserDefaults().setInteger(99, forKey: "HighestScore")` @AmenParham – BrikerMan Apr 22 '16 at 07:02
0

Thank you guys I got it yesterday but didn't find time to get on here and post it but here is the code that works. Thank You Guys again that helped!


class GameScene: SKScene {

    var score = Int()
    var highScore = Int()

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */


        //IntegerForKey will never return nil.  This will return 0 if there is no value.
        highScore = NSUserDefaults.standardUserDefaults().integerForKey("HighestScore")
        print("highScore - \(highScore)")


    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        /* Called when a touch begins */
        score += 1
        print("Score - \(score)")

        if score > highScore
        {
            highScore = score
            NSUserDefaults.standardUserDefaults().setObject(highScore, forKey:"HighestScore")
            NSUserDefaults.standardUserDefaults().synchronize()
            print("Beat")
        }

        else {
            print("Not Beat")
        }

    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}
Rishil Patel
  • 1,977
  • 3
  • 14
  • 30
Amen Parham
  • 73
  • 1
  • 8