数据处理-对象写入(2)

let p = Person()
p.name = "张三"
p.age = 12
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(p, forKey: "p1")
archiver.finishEncoding()
// 写个路径
let tmp = NSTemporaryDirectory()
let path = tmp + "index.txt"
print(path)
// 把data数据写入文件
data.write(toFile: path, atomically: true)

    // 解码
    
 let url = URL(fileURLWithPath: path)
  let data1 =  try! Data(contentsOf: url)
    print(data1)
 let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data)
 let p1 =  unarchiver.decodeObject(forKey: "p1") as! Person
    unarchiver.finishDecoding()
 print("p1.name = \(p1.name) p1.age = \(p1.age)")

你可能感兴趣的:(数据处理-对象写入(2))