Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Is not saving NSUserDefaults.standardUserDefaults values

I'm trying to save key value in the NSUserDefaults but is not been save. Here is my code:

func saveData() {

    let userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setObject("blablabla", forKey:"data")
    userDefaults.synchronize()
}

Any of you knows why this data is not been save?

I'll really appreciate your help.

like image 973
user2924482 Avatar asked Jul 05 '16 17:07

user2924482


2 Answers

Swift 2.x:

According with Apple sources:

public func objectForKey(defaultName: String) -> AnyObject?

to retrieve your value you could use:

if let value = userDefaults.objectForKey("data")  {
    // do whatever you want with your value
    // P.S. value could be numeric,string,..
}
like image 156
Alessandro Ornano Avatar answered Oct 09 '22 22:10

Alessandro Ornano


I think you are doing it wrong, try like this:

let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject("blablabla", forKey:"data")



let defaults = NSUserDefaults.standardUserDefaults()
if let name = defaults.stringForKey("data") {
    print(name)
}

You won't be able to access a string with dictionaryForKey because string is not a dictionary value type. Let me know if you need any further help.

like image 29
Tarvo Mäesepp Avatar answered Oct 09 '22 21:10

Tarvo Mäesepp