【发布时间】:2017-11-26 05:31:44
【问题描述】:
我有一些类: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 nsdata nskeyedarchiver