gpt4 book ai didi

ios - 用户默认值不在 swift 3 中保存字典内容

转载 作者:搜寻专家 更新时间:2023-11-01 06:04:08 24 4
gpt4 key购买 nike

我正在尝试向字典中添加键和值,然后添加用户默认的字典并读回字典对象。我有两个问题,非常感谢您的帮助,

1) 为什么从用户默认值中读取的字典是空的?由于我向字典添加了一个键和一个值,难道不应该将它们保存到我从用户默认值检索的字典中吗?

let defaults = UserDefaults.standard;
var myDict = [String: String]()
myDict["key"] = "value"

defaults.setValue(myDict, forKey: "myDict")


let mydict2 = defaults.object(forKey: "myDict") as? [String: String] ?? [String:String]()
print(mydict2)

2) 如果字典将我创建的自定义类存储为值或键,那么如果字典是这样的话,我能对这段代码做些什么:

class Car {
var engineSize: Int
var color: String

init() {
engineSize = 2000
color = "blue"
}

}

class Boat {
var surfaceArea: Int
var weight: Int

init() {
surfaceArea = 3500
weight = 4000
}
}

var myDict = [Car: Boat]()

如何将第二个字典保存到用户默认值并从那里读取?

谢谢

编辑:

这是 ebby94 建议的答案:

var myDict = [String:String]()
myDict["key"] = "value";

let data = NSKeyedArchiver.archivedData(withRootObject: myDict)
UserDefaults.standard.set(data, forKey: "myDict")


func foo()

{
guard let archivedData = UserDefaults.standard.value(forKey: "myDict") as? Data
else
{
print("failed1")
return
}
guard var unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: archivedData) as? [String:String]
else
{
print("failed2")
return
}

print(unarchivedDictionary["key"]!)
}

foo()

但是打印失败1,我假设数据没有正确归档。这可能是因为我在 Playground 上运行它吗?

最佳答案

如果您想首先将自定义对象保存到 userDefault,您需要对变量进行编码和解码,然后使用存档保存并使用取消存档获取数据。

class Car {
var engineSize: Int
var color: String

init() {
engineSize = 2000
color = "blue"
}
// Decode
required convenience public init(coder decoder: NSCoder)
{
self.init()

if let engineSize = decoder.decodeObject(forKey: "engineSize") as? Int
{
self.engineSize = engineSize
}
if let color = decoder.decodeObject(forKey: "color") as? String
{
self.color = color
}
}

// Encode
func encodeWithCoder(coder : NSCoder)
{
if let engineSize = self.engineSize
{
coder.encode(engineSize, forKey: "engineSize")
}
if let color = self.color
{
coder.encode(color, forKey: "weight")
}
}
}

class Boat {
var surfaceArea: Int
var weight: Int

init() {
surfaceArea = 3500
weight = 4000
}

// Decode
required convenience public init(coder decoder: NSCoder)
{
self.init()

if let surfaceArea = decoder.decodeObject(forKey: "surfaceArea") as? Int
{
self.surfaceArea = surfaceArea
}
if let weight = decoder.decodeObject(forKey: "weight") as? Int
{
self.weight = weight
}
}

// Encode
func encodeWithCoder(coder : NSCoder)
{
if let surfaceArea = self.surfaceArea
{
coder.encode(surfaceArea, forKey: "surfaceArea")
}
if let weight = self.weight
{
coder.encode(weight, forKey: "weight")
}
}

关于ios - 用户默认值不在 swift 3 中保存字典内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41842494/

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