1.遵守NSSecureCoding协议
2.实现协议的两个方法
//归档解归档代理
func encode(with aCoder: NSCoder){
aCoder.encode(name, forKey: "name")
aCoder.encode(age, forKey: "age")
aCoder.encode(score, forKey: "score")
}
required init?(coder aDecoder: NSCoder){
name = aDecoder.decodeObject(forKey: "name") as? String
age = aDecoder.decodeObject(forKey: "age") as? NSNumber
score = aDecoder.decodeObject(forKey: "score") as? NSNumber
}
3.自定义方法,读取和保存数据
//路径定义
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask
, true).first! as NSString
let filePath = path.appendingPathComponent("person.plist")
//保存和读取数据
func saveAccount(){
do {
//归档为data数据
let data = try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: true)
//将数据写入文件
try data.write(to: URL(fileURLWithPath: filePath))
} catch {
print(error)
}
}
class func loadAccount() -> UserAccount? {
print(filePath)
do {
//从本地文件读取data数据
let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
//解档数据
let account = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [UserAccount.classForKeyedUnarchiver()], from: data) as? UserAccount
return account
} catch {
print(error)
return nil
}
}
网友评论