gpt4 book ai didi

ios - UserDefaults 编码失败

转载 作者:行者123 更新时间:2023-11-30 11:54:39 24 4
gpt4 key购买 nike

将复杂数据存储到 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()
}

有人可以让我知道我做错了什么吗?

谢谢

最佳答案

如果您的结构实现可编码,那么您最好使用 JSONEncoderJSONDecoder

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)
}

关于ios - UserDefaults 编码失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47956050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com