bogdan barbulescu bogdan barbulescu - 3 months ago 15
Swift Question

Can't retrieve Double value NSUserDefaults - Swift

I am trying to retrieve a Double value from NSUserDefaults and when I try to retrieve it, nothing prints in the console.

Am I doing anything wrong?

var hoursNinethKey = "hoursNinethViewControllerKey"
var hours:Double = 0.0

// save total number of hours in NSUserDefaults
NSUserDefaults.standardUserDefaults().setDouble(self.hours, forKey: "hoursNinethKey")
print("saving in NSUserDefaults\(self.hours)")
}



// retrieve hours from NSUserDefaults
if let hoursRetrieved = NSUserDefaults.standardUserDefaults().objectForKey(hoursNinethKey) as? Double {
self.hours = hoursRetrieved

print("Hours Retrieved is \(hoursRetrieved)")
print(self.hours)
// does not print anything in the console.

}

Answer

Two things:

1) Your save key is the string "hoursNinethKey" while your load key is "hoursNinethViewControllerKey".

2) You never "Save" once you set the value.

Here's working code:

class ViewController: UIViewController {

    let hoursNinethKey = "hoursNinethViewControllerKey"
    var hours:Double = 2.0

    override func viewDidLoad() {
        super.viewDidLoad()

        // save total number of hours in NSUserDefaults
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setDouble(hours, forKey: hoursNinethKey)
        print("saving in NSUserDefaults\(hours)")
        defaults.synchronize()

    }

    override func viewDidAppear(animated: Bool) {
        if let hoursRetrieved = NSUserDefaults.standardUserDefaults().objectForKey(hoursNinethKey) as? Double {
            self.hours = hoursRetrieved

            print("Hours Retrieved is \(hoursRetrieved)")
            print(self.hours)
        }
    }
}