swift 本地归档、解档储存
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") aCoder.score,27)">"score") }
// 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() } }
3. 实现归档把模型保存到本地Document文件夹:
3.1 获取本地Document路径,一般路径都设为全局变量,方便解档直接使用:
letuserAccountPath ="(NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, SearchPathDomainMaskuserDomainMasktrue).first!)/userAccount.data" 3.2 对获取到的模型进行归档操作,要注意模型必须是确定的类型,如果是可选类型会报发送未识别的消息的错误(切记) NSKeyedArchiverarchiveRootObject(userModel!,toFile:userAccountPath) 4.实现解档从Document文件夹获取本地模型数据 4.1 判断Document文件夹下是否有已保存好的模型,有的话就解档取出模型
ifNSKeyedUnarchiver.unarchiveObject(withFile:userAccountPath) !=nil{
userModel=NSKeyedUnarchiverunarchiveObject(withFile:userAccountPath)as?HCUserModel } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |