1.对用户的模型数据(自定义类:HCUserModel)进行归档和解档
1.1 需要遵循NSCoding协议
1.2 需要实现funcencode(with aCoder:NSCoder){}归档方法
1.3需要实现requiredinit(coder aDecoder:NSCoder){}解档方法
1.4 重写init方法
2.HCUserModel的数据内容如下:
importUIKit
classHCUserModel:NSObject,NSCoding{
varid:Int?
varnickname:String?
varphone:varaccount:varpassword:vartype:varicon:varattentionnumber:varregistertime:varqrcode:varsignature:vardynamicstruts:varscore:Int?
// MARK:-处理需要归档的字段
funcencode(with aCoder:NSCoder) {
aCoder.encode(id,forKey:"id")
aCoder.nickname,27)">"nickname")
aCoder.phone,27)">"phone")
aCoder.account,27)">"account")
aCoder.password,27)">"password")
aCoder.type,27)">"type")
aCoder.icon,27)">"icon")
aCoder.attentionnumber,27)">"attentionnumber")
aCoder.registertime,27)">"registertime")
aCoder.qrcode,27)">"qrcode")
aCoder.signature,27)">"signature")
aCoder.dynamicstruts,27)">"dynamicstruts")
}
// MARK:-处理需要解档的字段
NSCoder) {
super.init()
id= aDecoder.decodeObject(forKey:"id")as?Int
nickname= aDecoder."nickname")String
phone= aDecoder."phone")account= aDecoder."account")password= aDecoder."password")type= aDecoder."type")icon= aDecoder."icon")attentionnumber= aDecoder."attentionnumber")registertime= aDecoder."registertime")qrcode= aDecoder."qrcode")signature= aDecoder."signature")dynamicstruts= aDecoder."dynamicstruts")score= aDecoder."score")Int
}
overrideinit() {
init()
}
}
letuserAccountPath ="\(NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,
SearchPathDomainMaskuserDomainMasktrue).first!)/userAccount.data"
3.2 对获取到的模型进行归档操作,要注意模型必须是确定的类型,如果是可选类型会报发送未识别的消息的错误(切记)
NSKeyedArchiverarchiveRootObject(userModel!,toFile:userAccountPath)
4.1 判断Document文件夹下是否有已保存好的模型,有的话就解档取出模型
ifNSKeyedUnarchiver.unarchiveObject(withFile:userAccountPath) !=nil{
userModel=NSKeyedUnarchiverunarchiveObject(withFile:userAccountPath)as?HCUserModel
}