数据持久化代码如下:
//
// ViewController.swift
// 归档解档
//
// Created by Mac on 2022/3/23.
//
importUIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.saveData()
self.loadData()
}
@discardableResult
//解档 反归档
funcloadData() ->UserAccount{
varfirstUserAccount =UserAccount()
letfullPath =getPath().appendingPathComponent("meals")
ifletnsData =NSData(contentsOf: fullPath) {
do{
letdata =Data(referencing:nsData)
firstUserAccount =tryNSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)as!UserAccount
print("name:\(String(describing: firstUserAccount.name))")
print("age:\(String(describing: firstUserAccount.age))")
print("sex:\(String(describing: firstUserAccount.sex))")
returnfirstUserAccount
}catch{
print("Couldn't read file.")
}
}
returnfirstUserAccount
}
//归档
funcsaveData() {
letuserModel =UserAccount()
userModel.name="good morning"
userModel.age="30"
userModel.sex="女"
letfullPath =getPath().appendingPathComponent("meals")
do{
let data = try NSKeyedArchiver.archivedData(withRootObject: userModel, requiringSecureCoding: false)
trydata.write(to: fullPath)
print("输出data:\(data)")
}catch{
print("faile to saveData ..............")
}
}
funcgetPath() ->URL{
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
returnpaths[0]
}
}
classUserAccount: NSObject,NSCoding{
varname:String?
varage:String?
varsex:String?
override init() {
super.init()
}
//编码 归档
funcencode(withcoder:NSCoder) {
coder.encode(self.name,forKey:"name")
coder.encode(self.age,forKey:"age")
coder.encode(self.sex,forKey:"sex")
}
//解码 返归档
requiredinit?(coderasCoder:NSCoder) {
self.name= asCoder.decodeObject(forKey:"name")as?String
self.age= asCoder.decodeObject(forKey:"age")as?String
self.sex= asCoder.decodeObject(forKey:"sex")as?String
}
}
网友评论