Swift学习

Swift-归档解归档

2019-06-28  本文已影响0人  千年一梦s
1.遵守NSSecureCoding协议
2.实现协议的两个方法
 //归档解归档代理
    func encode(with aCoder: NSCoder){
        aCoder.encode(name, forKey: "name")
        aCoder.encode(age, forKey: "age")
        aCoder.encode(score, forKey: "score")
    }
    
    required init?(coder aDecoder: NSCoder){
        name = aDecoder.decodeObject(forKey: "name") as? String
        age = aDecoder.decodeObject(forKey: "age") as? NSNumber
        score = aDecoder.decodeObject(forKey: "score") as? NSNumber
    }
3.自定义方法,读取和保存数据
//路径定义
    let path =   NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask
    , true).first! as NSString
    let filePath = path.appendingPathComponent("person.plist")

    //保存和读取数据
    func saveAccount(){
        do {
            //归档为data数据
            let data = try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: true)
            //将数据写入文件
            try data.write(to: URL(fileURLWithPath: filePath))
            
        } catch {
            print(error)
        }
        
    }
    class func loadAccount() -> UserAccount? {
        print(filePath)
        do {
            //从本地文件读取data数据
           let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
            //解档数据
           let account = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [UserAccount.classForKeyedUnarchiver()], from: data) as? UserAccount
           return account
        } catch {
            print(error)
            return nil
        }
    }
上一篇下一篇

猜你喜欢

热点阅读