Save dictionary in userdefaults in swift 3 with xcode 8

纵然是瞬间 提交于 2019-11-26 15:57:24

问题


I am using the following code to save an object to UserDefaults (previously 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 on the simulator.

For some reason this is not saving the value and 'nil' is printed. Wondering if it's a simulator problem.


回答1:


For Swift 3

UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")



回答2:


Working perfectly here 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;}



回答3:


This is the undocumented-but-known issue that NSUserDefaults/UserDefualts does not work in the iOS 10 simulator if the iOS 8/9 simulator has been previously run.

Rebooting your Mac and going straight to XCode 8, iOS 10 simulator will fix this issue.

See also: Why won't my app run in XCode 8 beta (8S128d)




回答4:


This problem seems to be caused by having two versions of xcode/simulator installed.

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

After following these steps the simulator is able to save to UserDefaults.




回答5:


Swift 4:-

let defaults = UserDefaults.standard

let dictionary: [String:String] = ["key":"Value"]  //Dictionary which you want to save

defaults.setValue(dictionary, forKey: "DictValue") //Saved the Dictionary in user default

let dictValue = defaults.value(forKey: "DictValue") //Retrieving the value from user default 

print(dictValue)  // Printing the value 


来源:https://stackoverflow.com/questions/37825630/save-dictionary-in-userdefaults-in-swift-3-with-xcode-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!