I\'m trying to store a dictionary in UserDefaults and always get app crash when the code runs. Here is the sample code which crashes the app when it is executed. I tried to
To store a NSDictionary (with non-string key) in NSUserDefaults you need to convert them to NSData first. Try this
let test = [1:"me"]
override func viewDidLoad() {
super.viewDidLoad()
let data = NSKeyedArchiver.archivedData(withRootObject: test)
let defaults = UserDefaults.standard
defaults.set(data, forKey: "dict1")
if let data2 = defaults.object(forKey: "dict1") as? NSData {
let dict = NSKeyedUnarchiver.unarchiveObject(with: data2 as Data)
print(dict)
}
}