gpt4 book ai didi

swift - 将对象作为类存储到文件中

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

我有一些类(class):A、B、C 以及描述:

class A {
var index: int = 0
init(){}
}

class B {
var a1 : A?
var a2 : A?
var relation : int?

init(){}
}

class C {
var vA : [A] = []
var vB : [B] = []

int(){
}
}

//在主程序中,为C设置数据

var c : C = C()

let a1 : A = A()
a1. index = 1
let a2 : A = A()
a2.index = 2

let b : B = B()
b.a1 = a1
b.a2 = a2
b.releation = 1

c.vA.append(a1)
c.vA.append(a2)

c.vB.append(b)

现在我想将“c”的数据存储到文件中,并在下次从该文件中再次取回。有什么解决办法吗?写入和读取文件或任何建议!

我尝试使用NSKeyedArchiver来存档数据,并使用NSKeyedUnArchiver再次取消存档数据,但是,当检查文件时总是“找不到文件”,和“始终返回 NIL”

            var c1 = c
let dataArchive : Data = Data(bytes: &c1, count: MemoryLayout<C>.stride)

let randomFilename = UUID().uuidString
let data = NSKeyedArchiver.archivedData(withRootObject: dataArchive)
let fullPath = getDocumentsDirectory().appendingPathComponent(randomFilename)

do {
try data.write(to: fullPath)
} catch {
print("Couldn't write file")
}

let filemgr = FileManager.default
if filemgr.fileExists(atPath: fullPath.absoluteString) {
print("File exists")
} else {
print("File not found")
}
//
var dataArchiveLoaded : Data?
let x = NSKeyedUnarchiver.unarchiveObject(withFile: fullPath.absoluteString)
print(x) //ALWAYS return NIL

最佳答案

如果您使用的是 Swift 4,您始终可以使类文件符合 Codable ,完成后,您只需使用 JSONEncoderJSONDecoder 分别对对象进行编码和解码。然后可以将编码数据保存到文件中。如果您想查看一些代码,请告诉我:)

关于swift - 将对象作为类存储到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47493373/

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