swift 归档解档操作

来源:互联网 发布:php用qq邮箱发送邮件 编辑:程序博客网 时间:2024/06/05 18:08

import UIKit

class MallrroNurseInformation: NSObject,NSCoding {
let userAccountPath = “(NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,FileManager.SearchPathDomainMask.userDomainMask,true).first!)/userAccount.data”

var name = String() //归档对象的属性值

// MARK:- 处理需要归档的字段
func encode(with aCoder:NSCoder
) {
aCoder.encode(“zhangsan”, forKey:”name”)
}

// MARK:- 处理需要解档的字段
required init(coder aDecoder:NSCoder
) {

super.init()
self.name = (aDecoder.decodeObject(forKey:”name”)as?String)!
}

override init() {

super.init()
}

//归档模型对象 personModel – 归档对应对象类(自己创建)
func archiveObject(pModel:personModel) -> Void {
NSKeyedArchiver.archiveRootObject(pModel, toFile:userAccountPath as String)
}

//读取模型对象
func unarchiveObject() -> personModel{
if (NSKeyedUnarchiver.unarchiveObject(withFile:userAccountPath as String) != nil) {
return (NSKeyedUnarchiver.unarchiveObject(withFile:userAccountPath as String)as? personModel)!
}
return self
}
}