将复杂数据存储到UserDefaults时,我得到一个例外。代码如下。
当写入变量c时会发生异常。
struct MyData : Codable {
var v1 : Int
var v2 : Int
var v3 : Int
}
final class AllData : NSObject {
var a : Int = 0
var b = [String : Int]()
var c = [String : MyData]()
func loadSettings()
{
let userDefaults = UserDefaults.standard
if let v = userDefaults.object(forKey: “A”) as? Int {
self.a = v
}
if let v = userDefaults.object(forKey: “B”) as? [String : Int] {
self.b = v
}
guard let decodedNSData = userDefaults.object(forKey: “C”) as? NSData,
let v = (NSKeyedUnarchiver.unarchiveObject(with: decodedNSData as Data) as? [String : MyData]? )!
else {
print("Failed decoding level information")
return
}
self.c = v
}
func saveSettings()
{
let userDefaults = UserDefaults.standard
userDefaults.set(self.a, forKey: “A”)
userDefaults.set(self.b, forKey: “B”)
userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: self.c), forKey: “C”)
userDefaults.synchronize()
}
有人可以让我知道我做错了吗?
谢谢
答案 0 :(得分:0)
如果您的struct实现可编码,那么最好使用 JSONEncoder &的 JSONDecoder 强>
struct Language: Codable {
var name: String
var version: Int
}
let swift = Language(name: "Swift", version: 4)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(swift) {
// save `encoded` somewhere
}
if let encoded = try? encoder.encode(swift) {
if let json = String(data: encoded, encoding: .utf8) {
print(json)
}
let decoder = JSONDecoder()
if let decoded = try? decoder.decode(Language.self, from: encoded) {
print(decoded.name)
}