Swift: does not store NSUserDefaults.standardUserDefaults values

I am trying to save a key value in NSUserDefaults, but it is not saved. Here is my code:

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

Do any of you know why this data was not saved?

I will be very grateful for your help.

+5
source share
3 answers

Swift 2.x:

According to Apple sources:

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

to get your value that you could use:

 if let value = userDefaults.objectForKey("data") { // do whatever you want with your value // PS value could be numeric,string,.. } 
+5
source

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 cannot access a string using dictionaryForKey because the string is not a type of dictionary value. Let me know if you need more help.

+4
source

You cannot access a string using a dictionary for a dictionary, because a string is not a type of dictionary value. You will need to use:

 if let savedString = userDefaults.stringForKey("data") { print(savedString) } 

If you have further questions, feel free to tell me :)

+2
source

All Articles