Save dictionary in userdefaults in swift 3 using xcode 8

I use the following code to save a UserDefaults object (formerly NSUserDefaults) using xcode 8:

let defaults = UserDefaults.standard() defaults.set(someObject, forKey: "someObject") print(defaults.object(forKey: "someObject")) 

someObject is a dictionary and I am running a simulator.

For some reason this does not save the value and it prints "nil". Wonder if this is a simulator problem.

+44
ios10 swift3 xcode8 nsuserdefaults
Jun 15 '16 at 3:33
source share
4 answers

This problem seems to be caused by the presence of two versions of xcode / simulator.

What worked for me was uninstalling xcode 7 and just saving xcode 8 beta on my system. Emptying garbage, resetting the simulator and starting. I also restarted the computer.

After completing these steps, the simulator can save to UserDefaults.

+8
Jun 15 '16 at 15:27
source share

For Swift 3

 UserDefaults.standard.setValue(token, forKey: "user_auth_token") print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)") 
+72
12 Aug '16 at 20:44
source share

Good work with this ..!

  let dict:[String:String] = ["key":"Hello"] UserDefaults.standard.set(dict, forKey: "dict") let result = UserDefaults.standard.value(forKey: "dict") print(result!) // Output -> { key:hello;} 
+26
Jun 15 '16 at 18:30
source share

This is an undocumented but well-known problem that NSUserDefaults / UserDefualts does not work in the iOS 10 simulator if the iOS 8/9 simulator was previously run.

By rebooting the Mac and switching directly to Xcode 8, the iOS 10 simulator will fix this problem.

See also: Why My Application Will Not Run in Xcode 8 beta (8S128d)

+10
Jun 15 '16 at 18:40
source share



All Articles