示例:创建单例ArchiveTest类使用归档、解档管理用户信息
存储和修改自定义对象的方法
let userinfo = ArchiveTest.shareInstance.usermode ?? UserModel()
userinfo.token = "123"
userinfo.name = "hel"
ArchiveTest.shareInstance.usermode = userinfo
ArchiveTest.shareInstance.saveAccount()
读取存储的数据
print(ArchiveTest.shareInstance.usermode?.token ?? "","name",ArchiveTest.shareInstance.usermode?.name ?? "")
//123 , hel
完整代码如下
ArchiveTest:归解档管理类
UserMode:自定义遵守NSCoding协议的数据模型类
class ArchiveTest : NSObject {
//单例
static let shareInstance:ArchiveTest = {
let instance = ArchiveTest()
//过滤文件是否不存在
let fileM = FileManager.default
if fileM.fileExists(atPath: instance.filePath) {
instance.loadAccount()
}
return instance
}()
private override init() {}
var tem:UserModel?
var usermode:UserModel? {
set{
tem = newValue
}
get{
return tem
}
}
//懒加载存储路径
lazy var filePath : String = {
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask
,true).first! as NSString
let filePath = path.appendingPathComponent("test.data")
return filePath
}()
//归档存储
func saveAccount() {
do{
if let a = usermode{
if #available(iOS 11.0, *) {
let data = try NSKeyedArchiver.archivedData(withRootObject: a, requiringSecureCoding: true)
try data.write(to:URL(fileURLWithPath:filePath))
}else{
// Fallback on earlier versions
}
}else{
print("usermode为空")
}
}catch{
print(error)
}
}
//解档获取
func loadAccount() {
do{
let data = try Data.init(contentsOf:URL(fileURLWithPath:filePath))
let model = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UserModel
self.usermode = model
}catch{
print("获取data数据失败:\(error)")
}
}
//清除所有归档数据
func cleanCache() {
self.usermode = UserModel()
saveAccount()
}
}
class UserModel: NSObject,NSCoding,NSSecureCoding {
static var supportsSecureCoding: Bool {
return true
}
var token:String?
var name:String?
func encode(with coder:NSCoder) {
coder.encode(token,forKey:"token")
coder.encode(name,forKey:"name")
}
required override init() {
super.init()
}
required init?(coder:NSCoder) {
token = coder.decodeObject(forKey:"token") as? String
name = coder.decodeObject(forKey:"name") as? String
}
}