iosswiftsklabelnode

How would I save a label using NSUserDefaults in swift?


I have these two UITextFields and the first texField subtracts the number from the second textField. It then takes the answer and puts it in my SKLabelNode. That works fine. But the problem Im having is that it doesn't save the label. When I quit the app and go back to it it doesnt save the value. What am I doing wrong with my code?

   override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    for touch in (touches as! Set<UITouch>) {
        var defaults=NSUserDefaults.standardUserDefaults()
        var save=defaults.integerForKey("saveCalories")


        var touch: UITouch = touches.first as! UITouch
        var location = touch.locationInNode(self)
        var node = self.nodeAtPoint(location)

        if let number1 = textFieldCaloriesIntake.text.toInt() {

            if let number2 = textFieldCaloriesBurned.text.toInt() {

                let subtract = number1 - number2

                defaults.setInteger(subtract, forKey: "saveCalories")


                var showTotalCalories = defaults.integerForKey("saveCalories")

                totalCaloriesLabel.text = String(showTotalCalories)
                NSUserDefaults.standardUserDefaults().synchronize()



            }




        }


      }

 }

Solution

  • Use this code for Swift

    NSUserDefaults.standardUserDefaults().setValue(value, forKey:key)
    

    Save example:

    NSUserDefaults.standardUserDefaults().setValue(positionTextField.text!, forKey: "position")
    

    Retrieve example:-

    position!.text=NSUserDefaults.standardUserDefaults().stringForKey("position")
    

    Note: remember the key for further retrievals