Unable to Write Swift Dictionary to NSUserDefaults

2019-05-17 17:58发布

问题:

I have been working on an app in which I user NSUserDefaults to persist a Dictionary for use elsewhere in the program. This been working perfectly since Beta 1. Now with the latest update (beta 5) this no longer works. It appears they have removed the ability to persist a swift Dictionary in this manner. However, I can persist an NSDictionary. Here is a code snippet that worked 2 days ago and now is broken.

var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(allPlayersDict, forKey: "playerDict")
userDefaults.synchronize()

This code does not write anything to the NSUserDefaults, not even the key, when checked using:

var testDict = NSUserDefaults.standardUserDefaults().dictionaryRepresentation()
println(testDict)

Has anyone else experienced this or have a solution?

回答1:

I have experienced the exact same issue since beta 5. Interestingly the code works fine when deploying it to a real iPhone 5s divice but It does not seem to work in the simulator.

Regards