一 .遵守NSSecureCoding協(xié)議
二.實現(xiàn)協(xié)議方法?static var supportsSecureCoding: Bool 設置為true
? ? ? 實現(xiàn)func encode(withcoder: NSCoder) 和requiredinit?(coder: NSCoder)
三 使用NSKeyedArchiver和NSKeyedUnarchiver進行歸檔解檔操作
下面是代碼實現(xiàn):
//
//? Person.swift
//? TestSwift
//
//? Created by 李功驕 on 2022/4/22.
//
importFoundation
classPerson:NSObject,NSSecureCoding {//
? ? static var supportsSecureCoding: Bool {
? ? ? ? return true
? ? }
? ? required override init() {
? ? ? ? super.init()
? ? }
? ? funcencode(withcoder: NSCoder) {
? ? ? ? coder.encode(name, forKey:"name")
? ? ? ? coder.encode(age, forKey:"age")
? ? }
? ? requiredinit?(coder: NSCoder) {
? ? ? ? name = coder.decodeObject(forKey:"name")as?String
? ? ? ? age = coder.decodeObject(forKey:"age")as?Int
? ? }
? ? letfilePath:String= {
? ? ? ? letpath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask,true).first!asNSString
? ? ? ? letfilePath = path.appendingPathComponent("test.data")
? ? ? ? returnfilePath
? ? }()
? ? varage:Int? =0
? ? varname:String?
? ? func saveAccount() {
? ? ? ? letdata =try? NSKeyedArchiver.archivedData(withRootObject:self, requiringSecureCoding:true)
? ? ? ? try? data?.write(to: URL(fileURLWithPath:filePath))
? ? }
? ? funcloadAccount()? -> Person?{
? ? ? ? ifletdata =try? Data(contentsOf: URL(fileURLWithPath:filePath)) {
? ? ? ? ? ? letmodel =try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)as?Person
? ? ? ? ? ? returnmodel
? ? ? ? }else{
? ? ? ? ? ? returnnil
? ? ? ? }
? ? }
}